Dotnet generics constraint

When working with generics in dotnet (like templates in C++) there is something called “constraint” that limits the type of generic you can use.

Say you have a method

AreEqual bool<T>(T x, T y)
{
return x == y;
}

It will stop in the compiler since T isn’t necessarily comparable.  So we have to make sure T is.

AreEqual bool<T>(T x, T y) where T:IComparable
{
return x == y;
}

This example requries T to implement IComparable; i.e. int and string but not necessarily Customer.

Other constraints are “struct” constraining T to value types like int and enums, “class” for contraining to classes or “new()” for requiring a default constructor (constructor without parameter).  One can also constrain to inherit from a class and even send this class as a parameter like T.

The constraints are limited and I have often stepped into limitations I cannot recall right now.

More info here: http://msdn.microsoft.com/en-us/library/d5x73970%28VS.90%29.aspx.

Leave a Reply