From an instance, I might do this.
var obj= Activator.CreateInstance(GetType());
Not sure how to get typeof of the inherited class in a static base method though.
Is this the best way forward?
public static Method<T>() where T : SomeBase, new()
You could make the base class generic and close the generic in the derived class.
public abstract class CreatorOf<T> where T : CreatorOf<T>
{
public static T Create()
{
return (T)Activator.CreateInstance(typeof(T));
}
}
public class Inheritor : CreatorOf<Inheritor>
{
public Inheritor()
{
}
}
public class Client
{
public Client()
{
var obj = Inheritor.Create();
}
}
There are some who consider this to be an "anti-pattern", but I believe there are circumstances where it is an acceptable approach.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With