What does the new() do in the code below?
public class A<T> where T : B, new()
The new constraint specifies that a type argument in a generic class or method declaration must have a public parameterless constructor. To use the new constraint, the type cannot be abstract.
Beginning with C# 8.0, you can use the notnull constraint to specify that the type argument must be a non-nullable value type or non-nullable reference type. Unlike most other constraints, if a type argument violates the notnull constraint, the compiler generates a warning instead of an error.
C# allows you to use constraints to restrict client code to specify certain types while instantiating generic types. It will give a compile-time error if you try to instantiate a generic type using a type that is not allowed by the specified constraints.
This is a constraint on the generic parameter of your class, meaning that any type that is passed as the generic type must have a parameterless constructor.
So,
public class C : B
{
public C() {}
}
would be a valid type. You could create a new instance of A<C>
.
However,
public class D : B
{
public D(int something) {}
}
would not satisfy the constraint, and you would not be allowed to create a new instance of A<D>
. If you also added a parameterless constructor to D, then it would again be valid.
The new() constraint means T has to have a public parameterless constructor. Any calls to T() get turned into calls to various overloads of Activator.CreateInstance(). A more flexible approach (say, if the constructors need arguments, or are internal rather than public) is to use a delegate:
public class A<T> where T : B
{
public void Method(Func<T> ctor)
{
T obj = ctor();
// ....
}
}
// elsewhere...
public class C : B
{
public C(object obj) {}
}
public void DoStuff()
{
A<C> a = new A<C>();
object ctorParam = new object();
a.Method(() => new C(ctorParam));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With