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.
public abstract Base
{
protected int field1;
protected int field2;
....
protected Base() { ... }
}
Sometimes I need to clone the derived class. So my guess was, just make a virtual Clone
method in my base class and only override it in derived classes that have additional fields, but of course my Base
class wouldn't be abstract anymore (which isn't a problem since it only has a protected
constructor).
public Base
{
protected int field1;
protected int field2;
....
protected Base() { ... }
public virtual Base Clone() { return new Base(); }
}
public A : Base { }
public B : Base { }
The thing is, since I can't know the type of the derived class in my Base one, wouldn't this lead to have a
Base
class instance even if I call it on the derived ones ? (a.Clone();
) (actually after a test this is what is happening but perhaps my test wasn't well designed that's why I have a doubt about it)Is there a good way (pattern) to implement a base
Clone
method that would work as I expect it or do I have to write the same code in every derived class (I'd really like to avoid that...)
Thanks for your help
Found this question while trying to solve this exact problem, had some fun with LINQPad while at it. Proof of concept:
I got another idea using the Activator class:
But i would go for the Alexander Simonov answer.
You can add a copy constructor to your base class:
If performance is not important for your case, you can simplify your code by creating just one general clone method which can clone whatever to whatever if properties are same:
Just override the
Clone
and have another method toCreateInstance
then do your stuff.This way you could have only
Base
class avoiding generics.You could do something like this:
But i doubt that it will bring something useful. I'll create another example..