A useful method to copy properties from one object to another object which has common properties. This is useful is you have a design which uses DTO type objects. Rather than going and writing lines of copy type code you can make a single call to
ObjectCopier.CopyCommonProperties(object1, object2);
public static void CopyCommonProperties(object source, object destination)
{
var myObjectFields = destination.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (var pi in myObjectFields)
{
if (pi.CanWrite)
{
var sourcepi = source.GetType().GetProperty(pi.Name);
if (sourcepi != null && sourcepi.CanRead)
if (pi.PropertyType.FullName == sourcepi.PropertyType.FullName)
pi.SetValue(destination, sourcepi.GetValue(source, null), null);
}
}
}
Example Unit Test to show usage
More...