Search code examples
c#staticextension-methodslanguage-design

Why must C# extension methods be defined in static classes?


I understand that C# extension methods must be static. What I don't understand is why these extensions can't be defined in non static classes or generic ones?

Update: I am interested in the reason behind this design decision.


Solution

  • This is more of an observation than an answer, but...

    When you call an instance method, a reference to the object you are calling is pushed onto the stack as the first argument in your method call. That first argument is "this" and is done implicitly.

    When you define an extension method, you explicitly define a "this" as the first argument.

    Is it possible that method resolution would be confusing if you could define extension methods and instance methods in the same class i.e. defining methods with the same name and, in effect, the same parameters when the "this" parameter is included.