Skip to content

Instantly share code, notes, and snippets.

@ernestohs
Created February 26, 2013 17:03
Show Gist options
  • Save ernestohs/5040136 to your computer and use it in GitHub Desktop.
Save ernestohs/5040136 to your computer and use it in GitHub Desktop.
Clone & Shallow
public static class ObjectCopy
{
/// <summary>
/// Clone by Deep Reflection
/// </summary>
/// <typeparam name="T">Type</typeparam>
/// <param name="source">Source Object</param>
/// <returns>Clone of Source</returns>
public static T Clone<T>(this T source)
{
T Cloned = (T)Activator.CreateInstance(source.GetType());
(from Property in source.GetType().GetProperties() where Property.GetGetMethod() != null && Property.GetSetMethod() != null
select Property).ToList().ForEach(Property =>
{
if (!Property.PropertyType.GetInterfaces().Contains(typeof(ICollection)) && Property.Name != "Name") {
object PropertyValue = Property.GetGetMethod().Invoke(source, Property.GetGetMethod().GetParameters());
if (PropertyValue != null && PropertyValue is DependencyObject) {
PropertyValue = PropertyValue.Clone();
}
Property.GetSetMethod().Invoke(Cloned, new object[] { PropertyValue });
}
else if (Property.PropertyType.GetInterfaces().Contains(typeof(ICollection))){
ICollection CollectionValue = (ICollection)Property.GetGetMethod().Invoke(source, new object[] { });
Property.SetValue(Cloned, CollectionValue, null);
}
});
return Cloned;
}
/// <summary>
/// Shallow copy of an object. Child objects are only referenced, not cloned
/// </summary>
/// <typeparam name="T">Type</typeparam>
/// <param name="source">Source Object</param>
/// <returns>Clone of Source</returns>
public static T ShallowCopy<T>(this T source)
{
return source.ShallowCopy(true);
}
public static T ShallowCopy<T>(this T source, bool copyValidators)
{
if (source == null) return default(T);
T destination = (T)Activator.CreateInstance(source.GetType());
source.ShallowCopy(destination, copyValidators);
return destination;
}
/// <summary>
/// Shallow copy an object properties to another object
/// </summary>
/// <typeparam name="T">Type</typeparam>
/// <param name="source">Source Object</param>
/// <param name="destination">Destination object</param>
public static void ShallowCopy<T>(this T source, T destination, bool copyValidators)
{
(from Property in source.GetType().GetProperties()
where Property.GetGetMethod() != null && Property.GetSetMethod() != null
select Property).ToList().ForEach(Property =>
{
if (Property.Name != "Name" && (copyValidators || !Property.Name.Contains("Validator")))
{
object PropertyValue = Property.GetGetMethod().Invoke(source, Property.GetGetMethod().GetParameters());
Property.GetSetMethod().Invoke(destination, new object[] { PropertyValue });
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment