Create Generic Class Instance from Static Method in a Derived Class
- by user343547
I have a class in C# with a template and static method similar to
class BClass<T>
{
  public static BClass<T> Create()
  {
    return new BClass<T>();
  }
 }
From this I derive a class and specify a template parameter to the base class
class DClass : BClass<int> { }
A problem occurs when I try to use the static method to create an instance of D
class Program
{
  static void Main(string[] args)
  {
    DClass d = DClass.Create();
  }
}
Gives a compiler error "Cannot implicitly convert type 'Test.BClass<int ' to 'Test.DClass'."
Adding the below cast leads to a runtime casting exception.
DClass d = (DClass)DClass.Create();
Is there any succint way to allow the static method to create instances of the derived class? Ideally I would like the equivalent of a c++ typedef and I don't want the below syntax (which does work).
BClass<int> d = DClass.Create();