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.

Advertisements

~ by Luis Abreu on March 23, 2011.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: