A Nifty Extension Method for Mapping Property Values by Name

Here is a nice little C# extension method that allows you to copy all of the properties from one object to another where the names match.

SetPropertiesByName(this object target, object source)
{
PropertyInfo[] sourceProperties = source.GetType().GetProperties();
PropertyInfo[] targetProperties = target.GetType().GetProperties();
foreach (PropertyInfo targetField in targetProperties)
{
PropertyInfo sourceProperty =
(sourceProperties.Where(f => f.Name == targetField.Name)).FirstOrDefault();

if (sourceProperty.IsNotNull())
{
targetField.SetValue(target, sourceProperty.GetValue(source, null), null);
}
}
}

The usage looks this…

foo.SetPropertiesByName(bar);

I was using AutoMapper for this, but it was overkill for what I needed.

Leave a Reply

Your email address will not be published. Required fields are marked *