Why does Generic class signature requires specifying new() if type T needs instantiation ?
Posted
by this. __curious_geek
on Stack Overflow
See other posts from Stack Overflow
or by this. __curious_geek
Published on 2009-12-03T13:03:55Z
Indexed on
2010/05/01
7:17 UTC
Read the original article
Hit count: 143
I'm writing a Generic class as following.
public class Foo<T> :
where T : Bar, new()
{
public void MethodInFoo()
{
T _t = new T();
}
}
As you can see the object(_t) of type T is instantiated at run-time. To support instantiation of generic type T, language forces me to put new() in the class signature. I'd agree to this if Bar is an abstract class but why does it need to be so if Bar standard non-abstract class with public parameter-less constructor.
compiler prompts following message if new() is not found.
Cannot create an instance of the variable type 'T' because it does not have the new() constraint
© Stack Overflow or respective owner