Skip to content

Instantly share code, notes, and snippets.

@jonathascosta
Created January 14, 2013 09:38
Show Gist options
  • Select an option

  • Save jonathascosta/4528916 to your computer and use it in GitHub Desktop.

Select an option

Save jonathascosta/4528916 to your computer and use it in GitHub Desktop.
Copy properties from an object to another object
public void CopyProperties(object from, object to)
{
foreach (var p in ((object)from).GetType().GetProperties())
{
var toProperty = to.GetType().GetProperty(p.Name);
var fromValue = p.GetValue(from, null);
if (toProperty.PropertyType.IsValueType)
{
var convertedValue = Convert.ChangeType(fromValue, toProperty.PropertyType);
toProperty.SetValue(to, convertedValue, null);
}
else
CopyProperties(toProperty.GetValue(to, null), fromValue);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment