Monday, October 22, 2007

A quick note about Extension Methods

If you're ever adding extension methods to a generic type (like say, IEnumerable<T>), nothing says you have to keep the same constraints on T for your method. For example, maybe your method is only relevant for reference types.

Assume you have a simple class called Box<T> with a single property Contents of type T. Box is just a box (a wrapper) around an instance of some unconstrained type T. You could define something like:

public static bool IsNull<T>(this Box<T> box) where T : class //note the new constraint

Now our extension method will only apply to Boxes whose T is a reference type.
Box<string> sbox = new Box<string>("abc");
bool isNull = sbox.IsNull(); //this works

Box<int> ibox = new Box<int>(5);
isNull = ibox.IsNull(); //does not compile

For some reason I expected the extra constraints not to work and I was surprised when they did. Of course you can only make your extension method type parameter more constrained than the existing type.

No comments: