LA.NET [EN]

Mar 23

Generic and constructor constraints

Posted in Basics C# CLR      Comments Off on Generic and constructor constraints

In this post, we’ll talk about one last kind of constraints: the constructor constraint. Whenever you apply a type constraint to a generic type argument, the compiler ensures that it can only be replaced by a concrete type which does expose a public default constructor. Constructor constrains are specified through the new keyword, as you can see from the following snippet:

public class AnotherGenericConstraint<T> where T:new() {
    public T GetNew() {
        return new T();
    }
}

Without constructor constraints, there really wouldn’t be a way for the compiler to allow you to instantiate generic type to which a primary constraint struct *hasn’t* been applied. Btw, and since we talk about value types, it’s an error to specify both a struct and type constraint to a generic type argument:

public class AnotherGenericConstraint<T>
    where T:struct, new() { //compile error
    public T GetNew() {
        return new T();
    }
}

A final note: currently, there’s not way to specify the number of parameters a constructor may receive. And it seems like that won’t change in the future, meaning that we’re struck with parameterless constructors. And I guess this is all about generic constraints. Stay tuned for more.