Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Instantiate Generic Type in C# class [duplicate]

Pretty basic question in C#,

class Data<T>
 {
    T obj;

    public Data()
    {
      // Allocate to obj from T here
      // Some Activator.CreateInstance() method ?
      obj =  ???
    }
 }

How do i do this?

like image 859
fadini Avatar asked Jan 07 '10 23:01

fadini


1 Answers

YOU can use the new constraint in your generic class definition to ensure T has a default constructor you can call. Constraints allow you to inform the compiler about certain behaviors (capabilities) that the generic parameter T must adhere to.

class Data<T> where T : new()
{
    T obj;

    public Data()
    {
        obj = new T();
    }
}
like image 111
LBushkin Avatar answered Sep 27 '22 17:09

LBushkin