Type constraints new-keyword
suggest changeBy using the new() constraint, it is possible to require that a type argument have a public parameterless 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 Create() causes a compile-time error with the 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.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents