Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a C# base class call a sub class's constructor in a static member?

Tags:

c#

oop

I have an abstract generic class "BaseClass" and a class "SubClass" defined as such:

public class SubClass : BaseClass<SubClass>

I would like to define a static method in the base class with signature like this:

public static T GetSub() 

And then call this on the subclass so that it returns an instance of the subclass

SubClass sub = SubClass.GetSub();

GetSub will have to call the default constructor for the SubClass and then return the instance.

This is starting to seem a little crazy but I am at least curious to know if this is possible. I am very much a novice when it comes to C#'s more complicated OOP features so I really am just taking a shot in the dark here.

like image 531
Ben313 Avatar asked Dec 06 '25 19:12

Ben313


2 Answers

It's possible to make this work but it will require a bit of work on your part. The easiest way is to make this work is to give T the new constraint in the declaration of BaseClass

abstract class BaseClass<T> where T : new() {
  public static T GetSub() {
    return new T();
  }
}

Another way is to use Activator.CreateInstance

abstract class BaseClass<T> {
  public static T GetSub() { 
    return Activator.CreateInstance<T>();
  }
}

Functionally though this is little different than the original approach. The CreateInstance<T> method will just look for a parameterless constructor and invoke it. In fact the new T() call will typically compile down to an Activator.CreateInstance<T> call.

like image 62
JaredPar Avatar answered Dec 09 '25 08:12

JaredPar


This won't work. You have to create a virtual method in the base class, override in every subclass and make it return instance of that subclass.
Or you can use reflection to call GetType() and use Activator to create instance of the appropriate type. In this way you need only one method in the base class, but this is less efficient speed wise.

like image 26
user626528 Avatar answered Dec 09 '25 10:12

user626528