Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create instance of inherited in static base method?

Tags:

c#

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()
like image 652
sgtz Avatar asked Jan 19 '23 09:01

sgtz


1 Answers

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.

like image 80
Steve Rowbotham Avatar answered Jan 29 '23 23:01

Steve Rowbotham