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
[TestFixture]
public class ObjectCopierUnitTest
{
public class TestClass
{
public int Attribute1 { get; set; }
public String Attribute2 { get; set; }
public DateTime Attribute3 { get; set; }
}
[Test]
public void TextObjectCopier()
{
TestClass object1 = new TestClass();
object1.Attribute1 = 1;
object1.Attribute2 = "2";
object1.Attribute3 = DateTime.Now;
// ObjectCopier dones the same as the following
//TestClass object2 = new TestClass();
//object2.Attribute1 = object1.Attribute1;
//object2.Attribute2 = object1.Attribute2;
//object2.Attribute3 = object1.Attribute3;
//... for as many common Properties there are betwwen the objects
TestClass object2 = new TestClass();
ObjectCopier.CopyCommonProperties(object1, object2);
// test the code worked
Assert.AreEqual(object1.Attribute1, object2.Attribute1);
Assert.AreEqual(object1.Attribute2, object2.Attribute2);
Assert.AreEqual(object1.Attribute3, object2.Attribute3);
}
}