Possible Duplicate:
extension method requires class to be static
In .NET:
Why can't static method in non-static class be an extension method?
Possible Duplicate:
extension method requires class to be static
In .NET:
Why can't static method in non-static class be an extension method?
Eric Lippert will probably weigh in with a really good answer on this one, but the gist of it will probably be:
We decided it would be easier on both programmers and the compiler if we limit the number of places that you have to look for extension methods.
This policy tends to force users to put all of their extension methods into a few specific classes that are designated for this purpose.
Because, well, that's the way it is.
My guess would be that allowing static extension methods would complicate the language (every feature adds complexity of one type or another) while adding almost zero benefit. If you are defining a static method on String
for example, what's the benefit in doing so when you can simply define your own class with the same static method?
Instance level extension methods are useful because they work on the current state of a type instance. The static method has no context, so it would not provide any utility over a static method defined elsewhere aside from logical grouping (i.e., defining a String.IsNullOrFullOfSomeChar(char c)
would logically make sense to belong to the String
class, but aside from that there is no advantage. And yes, that would be a horrible method, just an example).
Extension methods came about as a result of LINQ. They were implemented to get LINQ working the way that the designers wanted. Static extensions were not required and, as such, they were not implemented.
It makes sense that a static class is required to have extension methods. The number one reason is that the static class is stateless ...i.e. you don't have to instance the class. ...but this is just my gut feeling. It wouldn't make sense to me otherwise.
I think, too, that forcing extension methods to reside in public/internal static classes reduces the cost of using them.
At compile time whenever you use the instance syntax sugar for extension methods, this is converted into a call to the static method (which defines the extension), and passes through your instance.
Apart from the nice syntax it's no different to implementing a static method and passing your instance through as an argument. This is exactly what happens. You can't do this with static classes, as you can't pass a static class as a parameter to a method.