Simple Reflection Based Assignment Using Extension Methods
Have you ever had two objects, of different types, and wished that C# could just be smart enough to realize that objA.FirstName should be assigned to objB.FirstName? For me this comes up quite a bit when working with WCF services. I don't want a service to directly expose my internal business object type, because that type might change on a different schedule than that of my data contract. So I often end up with objects that have identical property names, usually the service being a subset of the internal class, but obviously of different types. How can I handle assigning objDC from objInternal without writing a line of code (or generating a line of code) for every single property? Enter AssignFrom ... with this code, you'll get something as simple as objDC.AssignFrom(objInternal);
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Reflection; using System.Diagnostics; namespace TestCSharp { public static class ObjectExtensions { public static T AssignFrom<T>(this T obj, object from) { Type toType = obj.GetType(); Type fromType = from.GetType(); var toInfo = toType.GetProperties(); var fromInfo = fromType.GetProperties(); foreach (var fromProp in fromInfo) { bool assigned = false; foreach (var toProp in toInfo) { if (toProp.CanWrite && fromProp.CanRead && toProp.PropertyType.Equals(fromProp.PropertyType) && toProp.Name.Equals(fromProp.Name) && toProp.GetIndexParameters().Count() == 0 && fromProp.GetIndexParameters().Count() == 0) { toProp.SetValue(obj, fromProp.GetValue(from, null), null); assigned = true; } } Debug.Assert(assigned, string.Format( "Property {0} was not populated to the To object.", fromProp.Name)); } return obj; } } }