Skip to content

Instantly share code, notes, and snippets.

@odytrice
Last active July 27, 2018 10:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save odytrice/6d2a41ea6e49af1dee3639a4d2de1c73 to your computer and use it in GitHub Desktop.
Save odytrice/6d2a41ea6e49af1dee3639a4d2de1c73 to your computer and use it in GitHub Desktop.
Extension Method to Assign Object properties in an Optimistic way
public static class Extensions
{
[DebuggerStepThrough]
/// <summary>
/// Update properties with properties of the object Supplied (typically anonymous)
/// </summary>
/// <typeparam name="T">Type of Source Object</typeparam>
/// <param name="destination">Object whose property you want to update</param>
/// <param name="source">destination object (typically anonymous) you want to take values from</param>
/// <returns>Update reference to same Object</returns>
public static T Assign<T>(this T destination, object source, params string[] ignoredProperties)
{
if (ignoredProperties == null) ignoredProperties = new string[0];
if (destination != null && source != null)
{
var query = from sourceProperty in source.GetType().GetProperties()
join destProperty in destination.GetType().GetProperties()
on sourceProperty.Name.ToLower() equals destProperty.Name.ToLower() //Case Insensitive Match
where !ignoredProperties.Contains(sourceProperty.Name)
where destProperty.PropertyType.IsAssignableFrom(sourceProperty.PropertyType) //Properties can be Assigned
where destProperty.GetSetMethod() != null //Destination Property is not Readonly
select new { sourceProperty, destProperty };
foreach (var pair in query)
{
//Go ahead and Assign the value on the destination
pair.destProperty
.SetValue(destination,
value: pair.sourceProperty.GetValue(obj: source, index: new object[] { }),
index: new object[] { });
}
}
return destination;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment