I am sure this must be a duplicate, but I can't find the answer:
If I have two classes:
public class BASE
{
public BASE() {};
public abstract BASE clone();
}
public class CHILD : BASE
{
public CHILD() : base() {}
public override BASE clone()
{
return new CHILD();
}
}
I have to make an explicit conversion every time I want to clone an object of type CHILD like:
var a = new CHILD();
CHILD b = a.clone() as CHILD;
Is there a way to avoid this conversion? I would like to be able to write:
var original = new CHILD();
BASE copy1 = original.clone();
CHILD copy2 = original.clone();
Is this possible in C#?
Not by overloading
Clone- you can't overload a method just by changing its return type. Use a different method instead:If you want to enforce that behavior on all inherited classes you could make
BASEgeneric: