I have an abstract base class Base
which has some common properties, and many derived ones which implement different logic but rarely have additional fields.
Found this question while trying to solve this exact problem, had some fun with LINQPad while at it. Proof of concept:
void Main()
{
Person p = new Person() { Name = "Person Name", Dates = new List() { DateTime.Now } };
new Manager()
{
Subordinates = 5
}.Apply(p).Dump();
}
public static class Ext
{
public static TResult Apply(this TResult result, TSource source) where TResult: TSource
{
var props = typeof(TSource).GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (var p in props)
{
p.SetValue(result, p.GetValue(source));
}
return result;
}
}
class Person
{
public string Name { get; set; }
public List Dates { get; set; }
}
class Manager : Person
{
public int Subordinates { get; set; }
}