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; } } }
.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }