By using the new()
constraint, it is possible to enforce type parameters to define an empty (default) constructor.
class Foo
{
public Foo () { }
}
class Bar
{
public Bar (string s) { ... }
}
class Factory<T>
where T : new()
{
public T Create()
{
return new T();
}
}
Foo f = new Factory<Foo>().Create(); // Valid.
Bar b = new Factory<Bar>().Create(); // Invalid, Bar does not define a default/empty constructor.
The second call to to Create()
will give compile time error with following message:
'Bar' 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 'Factory'
There is no constraint for a constructor with parameters, only parameterless constructors are supported.