Skip to content

Instantly share code, notes, and snippets.

@lluisfranco
Last active April 14, 2023 11:30
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save lluisfranco/b49a8aacb21a20186880c2f474d88001 to your computer and use it in GitHub Desktop.
Save lluisfranco/b49a8aacb21a20186880c2f474d88001 to your computer and use it in GitHub Desktop.
Map - Copy base class properties to derived class
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;
}
@lluisfranco
Copy link
Author

lluisfranco commented Dec 15, 2022

You can use it in the derived class constructor:

public DerivedClass(BaseClass b)
{
    if (b == null) return;
    this.Map(b);
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment