Question

This question already has an answer here:

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?

Was it helpful?

Solution

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;
        }
     }

OTHER TIPS

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();
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top