Created
January 4, 2013 13:29
-
-
Save Daniel15/4452596 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <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