C# – What Does new() Do in `where T: new()`?

.netc++generics

What does the new() do in the code below?

public class A<T> where T : B, new()

Best Answer

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.

Related Question