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.
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.
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.
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