Skip to content

Instantly share code, notes, and snippets.

@ajai8085
Created January 23, 2017 21:34
Show Gist options
  • Save ajai8085/d3727dc444ae6acf410e41f57f1c9ae1 to your computer and use it in GitHub Desktop.
Save ajai8085/d3727dc444ae6acf410e41f57f1c9ae1 to your computer and use it in GitHub Desktop.
Shallow Copy public properties between unrelated objects which has same property name , this can also copy the fields from derived class to base class and maintain a pure base class object . (useful when passing parameter to dapper)
public static void CopyMatchingProperties<TResult, TInput>(this TInput input, TResult result)
where TResult : class
where TInput : class
{
var properties = typeof(TResult).GetProperties(BindingFlags.Instance | BindingFlags.Public).ToList();
var propertiesInput = typeof(TInput).GetProperties(BindingFlags.Instance | BindingFlags.Public).ToList();
properties.ForEach(p =>
{
var value = p.GetValue(input);
//if (value != null)
{
var pdest =
propertiesInput.FirstOrDefault(i => i.Name.Equals(p.Name) && p.PropertyType == i.PropertyType);
if (pdest != null)
{
pdest.SetValue(result, value);
}
}
});
}
public static TEntity CopyPropertisToNewInstance<TEntity>(this TEntity input)
where TEntity : class, new()
{
var result = new TEntity();
input.CopyMatchingProperties(result);
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment