Reputation: 13343
I have noticed someone has done this in C# - notice the new()
public class MyClass<T> where T: new(){
//etc
}
What does this achieve?
Upvotes: 6
Views: 141
Reputation: 2071
It enables you to type:
T obj = new T();
which would generate a compiler error without the new()
clause.
Upvotes: 1
Reputation: 755179
This constrains the generic MyClass<T>
to only work with T
instances that have an available parameterless constructor. This allows you to safely use the following expression within the type
new T()
Without the new
constraint this would not be allowed because the CLR couldn't verify the type T
had an applicable constructor.
Upvotes: 10
Reputation: 74410
It means that T must have a public parameterless constructor. For example (out of MSDN), the following creation of a new T object must be possible:
class ItemFactory<T> where T : new()
{
public T GetNewItem()
{
return new T();
}
}
For more info, please see new constraint in MSDN.
Upvotes: 4