Skip to content

Instantly share code, notes, and snippets.

@undrivendev
Last active May 11, 2018 08:42
Show Gist options
  • Save undrivendev/a315a8d1eedf934cffe80c05d5e468aa to your computer and use it in GitHub Desktop.
Save undrivendev/a315a8d1eedf934cffe80c05d5e468aa to your computer and use it in GitHub Desktop.
/// <summary>
/// copies the properties with the same name and type from the objectFrom to the objectTo.
/// Beware, it uses reflection, so it can be slow for certain scenarios
/// </summary>
public static void CopyObjectPropertyValues(object objectFrom, object objectTo)
{
var propertiesFrom = objectFrom.GetType().GetProperties();
var propertiesTo = objectTo.GetType().GetProperties();
foreach (var propFrom in propertiesFrom)
{
foreach (var propTo in propertiesTo)
{
if (propFrom.Name == propTo.Name && propFrom.PropertyType == propTo.PropertyType)
{
propTo.SetValue(objectTo, propFrom.GetValue(objectFrom));
break;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment