Last active
April 14, 2023 11:30
-
-
Save lluisfranco/b49a8aacb21a20186880c2f474d88001 to your computer and use it in GitHub Desktop.
Map - Copy base class properties to derived class
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
public static TT Map<TT, ST>(this TT target, ST source) where TT : class | |
{ | |
var tprops = typeof(TT).GetProperties().Where(x => x.CanWrite).ToList(); | |
tprops.Where(x => x.CanWrite).ToList().ForEach(prop => | |
{ | |
var sp = source.GetType().GetProperty(prop.Name); | |
var tp = target.GetType().GetProperty(prop.Name); | |
if (sp != null && tp != null) | |
{ | |
var value = sp.GetValue(source, null); | |
target.GetType().GetProperty(prop.Name).SetValue(target, value, null); | |
} | |
}); | |
return target; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You can use it in the derived class constructor: