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
MSDN's own page on where T : new()
lists the most common use case:
Apply the new constraint to a type parameter when your generic class creates new instances of the type, as shown in the following example:
class ItemFactory<T> where T : new()
{
public T GetNewItem()
{
return new T();
}
}
The constraint also requires that the parameterless constructor be public.
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:
public void DoWork<T>() where T : new() {
var thing = new T();
}
Vs:
public void DoWork<T>() {
var thing = new T(); - runtime says "wtf are you doing? i cant create a
new T because T might not have a public
parameterless constructor"
}
public T SomeMethod<T>(string item) where T : new();
Constraints "T" to be type having default (parameterless) contructor.
You won't be able to use this type (would fail to compile)
public class CustomTypeA{
public CustomTypeA(int count){}
}
while this one is allowed,
public class CustomTypeB{
}
and this one also,
public class CustomTypeC{
public CustomTypeC(){}
}
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.
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:
var instance = new T();
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 the Activator.CreateInstance
method yourself, however you have no guarantee that the type actually have a parameterless constructor unless you add the constraint.