Create Generic Class Instance from Static Method in a Derived Class

Posted by user343547 on Stack Overflow See other posts from Stack Overflow or by user343547
Published on 2010-05-27T11:45:50Z Indexed on 2010/05/27 11:51 UTC
Read the original article Hit count: 249

Filed under:
|
|

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();

© Stack Overflow or respective owner

Related posts about c#

Related posts about generics