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?
AdvancedAnswer
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.