views:

373

answers:

3

Pretty basic question in C#,

class Data<T>
 {
    T obj;

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

Not sure how to do this ? Thank you for any assistance.

+8  A: 

If you want to create your own instance of T, then you need define a constraint new()

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

    public Data()
    {
      obj =  new T();
    }
 }

If you want to pass in the obj then you need to allow it in the constructor

 class Data<T>
     {
        T obj;

        public Data(T val)
        {
          obj = val;
        }
     }
Stan R.
Answer is exactly what I was looking for too! Thanks!
DeanMc
A: 

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();
    }
}
LBushkin
A: 

Another possibility, not necessarily the right one

public class Data<T> : public T
{
    public Data()
    {
    }
}
kenny
This won't compile: you'll get the error "Cannot derive from 'T' because it is a type parameter."
itowlson