C # Generic Class <T>
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 to share