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
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With