Back to results for “Reflection”
C# › Attributes & Reflection

How would you write a simple reflection-based object mapper that copies matching property values from one object to another of a different type?

Advanced

Answer

Iterate the source type's properties via reflection, and for each one, look up a same-named property on the destination type; if found and type-compatible, read the source value with PropertyInfo.GetValue() and write it to the destination with PropertyInfo.SetValue() — this is conceptually what libraries like AutoMapper do internally, with much more sophistication and caching for performance.
public static TDest MapTo<TSource, TDest>(TSource source) where TDest : new() {
  var dest = new TDest();
  var destProps = typeof(TDest).GetProperties();
  foreach (var srcProp in typeof(TSource).GetProperties()) {
    var destProp = destProps.FirstOrDefault(p => p.Name == srcProp.Name && p.PropertyType == srcProp.PropertyType);
    destProp?.SetValue(dest, srcProp.GetValue(source));
  }
  return dest;
}
Real-world example Building a lightweight DTO-to-entity mapper for a small project without pulling in a full mapping library dependency.

Common follow-ups: Why would a production-grade mapper like AutoMapper compile and CACHE this mapping logic instead of using raw reflection on every call?