Archive for June, 2010

Extension Methods and Static Generic Classes

June 15, 2010 1 comment

This post refers to a question on Stackoverflow that I tried to answer a while ago and that still hasn’t received an accepted answer: Why is it impossible to declare extension methods in a generic static class?

Against popular belief, static generic classes are not a problem here, they are perfectly legal but not for declaring extensions methods. The original motivation of the person asking this question was to declare a static generic class defining a constrained generic type parameter once, so the constraints wouldn’t have to be repeated on each declared extension methods.

Consider the following extensions methods:

public static class ExtensionsForIMyInterface
public static void DoSomething(this IEnumerable source) where T : IMyInterface {};
public static void DoSomethingElse(this IEnumerable source) where T : IMyInterface {};

The purpose of this class is to provide extension methods for all types implementing IMyInterface. As you can clearly see, this constraint has to be repeated on every extensions method. If declaring extension method inside static generic classes would be allowed, we could add easily avoid repeating the constraint:

public static class ExtensionsForIMyInterface where T : IMyInterface
public static void DoSomething<T>(this IEnumerable<T> source) {};
public static void DoSomethingElse<T>(this IEnumerable<T> source) {};

But we can’t, so what’s the reason for this constraint?

Gorpik made a good point by mentioning that it would prove difficult for the compiler to locate non-generic extension methods on a static generic class. This would be the scenario:

static class GenStatic<T>
static void ExtMeth(this Class c) {/*...*/}

Class c = new Class();
c.ExtMeth(); // Equivalent to GenStatic.ExtMeth(c); what is T?

This is probably the best justification for the constraint because allowing the declaration of extension methods on static generic classes would make it necessary to constrain those classes to declare generic methods only. Adding yet another special case to provide a little syntactic sugar would pollute the cleanliness of the language design.

Categories: .NET, Design
%d bloggers like this: