Is it possible to get a new instance of the current derived class that is calling a function of the base abstract class? For example:
class Bar1 : Foo
{
}
class Bar2 : Foo
{
}
abstract class Foo
{
public Foo CreateAnotherInstance()
{
return new Bar1/Bar2(); // depending on the calling derived class
}
}
Should lead to:
Bar1 bar1 = new Bar1();
Bar2 bar2 = new Bar2();
Foo bar1_2 = bar1.CreateAnotherInstance(); // Should be a new Bar1 instance
Foo bar2_2 = bar1.CreateAnotherInstance(); // Should be a new Bar2 instance
The only way i've found is to create the instance is an abstract method, where the instance is created in each derived class like:
class Bar1 : Foo
{
public override Foo CreateAnotherInstance()
{
return new Bar1();
}
}
class Bar2 : Foo
{
public override Foo CreateAnotherInstance()
{
return new Bar2();
}
}
abstract class Foo
{
public abstract Foo CreateAnotherInstance();
}
But in this way, i have to create the method for each derived class.
Is there a simpler solution for this problem available?
Thanks to René Vogt and mjwills for giving the answer:
Using
(Foo)Activator.CreateInstance(GetType());
So change the abstract class to:
abstract class Foo
{
public Foo CreateAnotherInstance()
{
return (Foo)Activator.CreateInstance(GetType());
}
}
If the constructor isn't parameterless:
(Foo)Activator.CreateInstance(GetType(), para1, para2, ...);