The following code:
private IList<T> DoStuff<T>()
{
IList<T> res = new List<T>();
for (int i = 0; i < 10; i++)
{
T item = DoOtherStuff<T>();
res.Add(item);
}
return res;
}
private T DoOtherStuff<T>() where T : new()
{
return new T();
}
Generates the following error:
‘T’ must be a non-abstract type with a public parameterless constructor in order to use it as parameter ‘T’ in the generic type or method ‘DoOtherStuff()’
Please may somebody explain why?
Change
to
since otherwise you can’t guarantee that
Thas anew()constructor.