ObjectCopier to Copy Common Properties between objects

by Kevin Bosch 9. August 2011 20:11

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

Tags: , ,

DataTable

Calendar

<<  May 2012  >>
MoTuWeThFrSaSu
30123456
78910111213
14151617181920
21222324252627
28293031123
45678910

View posts in large calendar
Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2012 Code Associate