Skip to content

Instantly share code, notes, and snippets.

@Daniel15
Created January 4, 2013 13:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Daniel15/4452596 to your computer and use it in GitHub Desktop.
Save Daniel15/4452596 to your computer and use it in GitHub Desktop.
/// <summary>
/// Copy shared properties from <paramref name="source"/> to <paramref name="dest"/>.
/// Shared properties are those that both types have.
/// This is similar to AutoMapper which only works on .NET 4
/// </summary>
/// <typeparam name="TSource">Source type</typeparam>
/// <typeparam name="TDest">Destination type</typeparam>
/// <param name="source">Source object</param>
/// <param name="dest">Destination object</param>
/// <returns>Destination object with all the shared properties copied over</returns>
public static TDest CopyPropertiesTo<TSource, TDest>(TSource source, TDest dest)
{
var sourceType = typeof(TSource);
var destType = typeof(TDest);
// Find all the writable properties on TDest
var destProps = destType.GetProperties(BindingFlags.Public | BindingFlags.Instance)
.Where(prop => prop.CanWrite)
.Select(prop => prop.Name);
// Find the readable properties on TSource
var sourceProps = sourceType.GetProperties(BindingFlags.Public | BindingFlags.Instance)
.Where(prop => prop.CanRead)
.Select(prop => prop.Name);
// Find the properties the two have in common
var sharedProps = sourceProps.Intersect(destProps);
// Copy the source properties to the destination object
foreach (var prop in sharedProps)
{
var sourceProp = sourceType.GetProperty(prop);
var destProp = destType.GetProperty(prop);
var value = sourceProp.GetValue(source, null);
destProp.SetValue(dest, value, null);
}
return dest;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment