1

I mean, I'm pretty sure it is a good habit anyway, but are there any technical/conceptual reasons why this is enforced by the compiler? Or is it enforcing aesthetics only?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Dirk Boer
  • 8,522
  • 13
  • 63
  • 111
  • 2
    possible duplicate http://stackoverflow.com/questions/3930335/why-are-extension-methods-only-allowed-in-non-nested-non-generic-static-class?lq=1 http://stackoverflow.com/questions/2618271/why-is-it-impossible-to-declare-extension-methods-in-a-generic-static-class?lq=1 http://stackoverflow.com/questions/2731695/extension-method-requires-class-to-be-static?lq=1 – MichaC Oct 05 '13 at 16:41
  • Perhaps it speeds up searching for extension methods in the compiler since it needs to look at fewer. But I'm not sure if tagging the classes with attributes wouldn't work better, or if it actually matters at all (you only need to walk once, after that read from an indexed cache) – CodesInChaos Oct 05 '13 at 16:48

2 Answers2

1

There are no reasons for this behavior below the C# layer. Starting with the IL layer extension methods and static classes do not exist (except for either unimportant changes or custom attributes).

It is a choice the language designers made, supposedly for code clarity. It does not have to be this way for any fundamental reason.

There are other similar restrictions as well. For example you can't have extensions defined in nested classes.

usr
  • 168,620
  • 35
  • 240
  • 369
1

For my understanding this is a conceptual move.

The static class acts like a pure container for methods and itself does not represents the object, and the extension method by itself is the method that only processes the input and does not acts like a part of the objects behavior.

That is why I think they are very similar by its nature in the C# and probably that is why they where linked together by the language.

Oleg Karasik
  • 959
  • 6
  • 17