C # Generic Class <T>

How do I add a shared list to my list? I tried to create a T object, but that doesn't work either.

class Bar<T> where T : IDrink
{
    List<T> storage = new List<T>();

    public void CreateDrink()
    {
        storage.Add(T); //<- This doesn't work
    }
}

      

+3


source to share


2 answers


T

is a type that is not an instance of that type. So you need a parameter in, CreateDrink

or use a factory method that returns a new instance T

.

If you want to instantiate the general constraint should include new()



class Bar<T> where T : IDrink, new()
{
    List<T> storage = new List<T>();

    public void CreateDrink()
    {
        storage.Add(new T()); 
    }
}

      

The new constraint specifies that any type argument in a generic class declaration must have a public, parameterless constructor. Use a new constraint, the type cannot be abstract.

+5


source


You can do it like:



storage.Add(Activator.CreateInstance<T>()); 

      

+3


source







All Articles