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
[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); } }

Tags: , ,

DataTable

Comments


August 20. 2011 12:40
Cute Love Quotes
Spot on with this write-up, I actually think this website wants way more consideration. I’ll most likely be again to read far more, thanks for that info.

Comments are closed

Calendar

<<  February 2012  >>
MoTuWeThFrSaSu
303112345
6789101112
13141516171819
20212223242526
2728291234
567891011

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