Creating a Cloned Copy of Subclass from Base Class in C#

c++reflection

Consider this scenario:

public class Base
{
    public int i;
}

public class Sub : Base
{
    public void foo() { /* do stuff */}
}

And then I want to, given an instance of Base get an cloned instance of Sub (with i=17 in this case) so that I can call foo in the subclass.

Base b = new Base { i=17 };
Sub s = CloneAndUpcast(b);
s.foo();

However, how can I create CloneAndUpcast?

I am thinking that is should be possible to recursively clone all of Base-members and properties using reflection. But quite some work.

Anyone with better, neater ideas?

PS. The scenario where I am thinking about using this is a set of "simple" classes in a tree-like structure (no cyclic graphs or similar here) and all the classes are simple value holders. The plan is to have a stupid layer holding all values and then an similar set of classes (the subclasses) that actually contains some business-logic the value-holders shouldn't be aware of. Generally bad practice yes. I think it works in this case.

Best Answer

You could use AutoMapper to avoid the tedium of writing the copy constructors.

public class MyClass : MyBase
{
    public MyClass(MyBase source)
    {
        Mapper.Map(source, this);
    }
}

and you need to run this once when your application starts up

Mapper.CreateMap<MyBase, MyClass>();

You can download AutoMapper from https://github.com/AutoMapper/AutoMapper

Related Question