Is it possible to create an abstract method that must return an instance of the derived class? I can do this:
abstract class Base
{
public abstract Base GetObj();
}
class Derived : Base
{
public Derived() { }
public override Base GetObj()
{
return new Derived();
}
}
But I was wondering if there was a way to do it such that Derived::GetObj() is forced to return a Derived?
Thanks.
Using generics should make this possible:
You could even simplify this even more (if all of the derived instances are created with default constructors):