Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Generic Class<T>

How can I add a generic Type to my list? I tried to create an object of T but this doesn't work neither.

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

    public void CreateDrink()
    {
        storage.Add(T); //<- This doesn't work
    }
}
like image 293
Danixo Avatar asked Apr 25 '26 18:04

Danixo


1 Answers

T is a type not an instance of that type. So you need a parameter in CreateDrink or use a factory method that returns a new instance of T.

If you want to create an instance the generic constraint must 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. To use the new constraint, the type cannot be abstract.

like image 191
Tim Schmelter Avatar answered Apr 28 '26 09:04

Tim Schmelter