Skip to content

Instantly share code, notes, and snippets.

@arman-hpp
Last active May 8, 2016 09:00
Show Gist options
  • Save arman-hpp/4e6fab59524f4a53d1ca3ffd3caeedb5 to your computer and use it in GitHub Desktop.
Save arman-hpp/4e6fab59524f4a53d1ca3ffd3caeedb5 to your computer and use it in GitHub Desktop.
CopyFrom
public static class Ex
{
public static T CopyFrom<T>(this T objTarget, T objSource)
{
var typeSource = objSource.GetType();
var propertyInfo = typeSource.GetProperties();
foreach (var property in propertyInfo.Where(property => property.CanWrite))
{
if (property.PropertyType.IsPrimitive())
{
property.SetValue(objTarget, property.GetValue(objSource, null), null);
continue;
}
var objSourcePropertyValue = property.GetValue(objSource, null);
if (objSourcePropertyValue != null)
{
var objTargetPropertyValue = property.GetValue(objTarget, null);
if (objTargetPropertyValue == null)
{
objTargetPropertyValue = Activator.CreateInstance(objSourcePropertyValue.GetType());
property.SetValue(objTarget, objTargetPropertyValue, null);
}
if (property.PropertyType.IsEnumerable())
{
var addMethod = objTargetPropertyValue.GetType().GetMethod("Add");
if (addMethod == null)
continue;
foreach (var srcItem in (IEnumerable) objSourcePropertyValue)
{
var desItem = Activator.CreateInstance(srcItem.GetType());
desItem.CopyFrom(srcItem);
addMethod.Invoke(objTargetPropertyValue, new[] { desItem });
}
continue;
}
objTargetPropertyValue.CopyFrom(objSourcePropertyValue);
}
else
{
property.SetValue(objTarget, null, null);
}
}
return objTarget;
}
public static bool IsPrimitive(this Type propertyType)
{
return propertyType.IsValueType || propertyType.IsEnum || propertyType == typeof (string);
}
public static bool IsEnumerable(this Type propertyType)
{
return typeof(IEnumerable).IsAssignableFrom(propertyType);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment