Skip to content

Instantly share code, notes, and snippets.

@derekgates
Created January 7, 2014 19:49
Show Gist options
  • Save derekgates/8305638 to your computer and use it in GitHub Desktop.
Save derekgates/8305638 to your computer and use it in GitHub Desktop.
ClonePublicPropertiesAndFields() clones all properties and fields of a given class; practically making a shallow copy.
/// <summary>
/// Clones all public properties and fiels on one object to another (excluding index based properties). The properties
/// must have the same name scheme. Type does not matter.
/// </summary>
/// <param name="o"></param>
/// <param name="destination">Where to clone the properties to.</param>
public static void ClonePublicPropertiesAndFields(this object o, object destination)
{
if (destination == null) throw new ArgumentNullException("destination", "Destination cannot be null!");
Type otype = o.GetType(),
dtype = destination.GetType();
foreach (PropertyInfo p in otype.GetProperties())
{
if (p.CanRead)
{
var dp = dtype.GetProperty(p.Name);
if (dp != null && dp.CanWrite)
dp.SetValue(destination, p.GetValue(o, null), null);
}
}
foreach (FieldInfo fi in otype.GetFields())
{
var df = dtype.GetField(fi.Name);
if (df != null)
df.SetValue(destination, fi.GetValue(o));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment