I am trying to identify various uses cases
of using new()
in statement
public T SomeMethod<T>(string item) where T : new();
I know compiler will ensure that T
must have a default constructor. But in what all scenario this is helpful.
I have gone through this link
It's helpful if anywhere in your code you need to create a new instance of T - for example, in a generic factory method. If you don't ensure a parameterless constructor, your code can never create an instance (since you don't know what the constructor signature will look like).
It's useful if your generic method/class will have to create an instance of the given type. If you had a method that created a generic type:
Vs:
Constraints "T" to be type having default (parameterless) contructor.
You won't be able to use this type (would fail to compile)
while this one is allowed,
and this one also,
Also note, this type of constrain would accept all Struct T's (int,double etc). Because structs always have a default contructor.
Given these possiblitis, It is useful : 1) when you want to constraint to above list. 2) when you want to instantiate (call its constructor) such type without using reflection.
MSDN's own page on
where T : new()
lists the most common use case:The constraint also requires that the parameterless constructor be public.
The point of this constraint is that the compiler will guarantee that any type you specify for
T
will have a public parameterless constructor, allowing this code to work:Note, however, that the above code will in fact turn into a call to
Activator.CreateInstance(Type)
, which means that the guarantee is all you get. You could call theActivator.CreateInstance
method yourself, however you have no guarantee that the type actually have a parameterless constructor unless you add the constraint.