Copy all public properties from an object to another object
I often ran into situation where I need to copy all the value of an object into another object, this normally happen in ORM related project where you need the value to be copy from an entity to an entity retrived from db (ActiveRecord) kind of entity, so I created a simple extension method to facilitate this action.
///Let say I have 2 User object user1 and user2, all I needed to do is/// Copy the speficied public properties from source to target. /// ///Type of object. /// Target object to copy to./// Source object to copy from.///Target object with each public properties copied from source object. public static T CopyFrom(this T target, object source) { var sourceObjType = source.GetType(); //loop through each public properties in the type foreach (var targetProperty in target.GetType().GetProperties()) { var sourceProperty = sourceObjType.GetProperty(targetProperty.Name); if (sourceProperty != null) // match found { // check types and take care of Nullable type. var sourceType = Nullable.GetUnderlyingType(sourceProperty.PropertyType) ?? sourceProperty.PropertyType; var targetType = Nullable.GetUnderlyingType(targetProperty.PropertyType) ?? targetProperty.PropertyType; if (targetType.IsAssignableFrom(sourceType)) { targetProperty.SetValue(target, sourceProperty.GetValue(source, null), null); } } } return target; }
user1.CopyFrom(user2);One catch to take note is retrieving the object's type for comparison before actually copying the value. The catch is to use Nullable.GetUnderlyingType, otherwise Nullable type will always return null.
Comments
Post a Comment