Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 241
Mehran Avatar asked Aug 23 '11 15:08

Mehran


2 Answers

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.

like image 58
Tim Lloyd Avatar answered Nov 15 '22 16:11

Tim Lloyd


Take a look to this piece of the .NET C# specification:

When the first parameter of a method includes the this modifier, that method is said to be an extension method. Extension methods can only be declared in non-generic, non-nested static classes. The first parameter of an extension method can have no modifiers other than this, and the parameter type cannot be a pointer type.

And this fragment from Jon Skeet's answer:

It's not clear to me why all of these restrictions are necessary - other than potentially for compiler (and language spec) simplicity. I can see why it makes sense to restrict it to non-generic types, but I can't immediately see why they have to be non-nested and static. I suspect it makes the lookup rules considerably simpler if you don't have to worry about types contained within the current type etc, but I dare say it would be possible.

like image 35
Daniel Peñalba Avatar answered Nov 15 '22 16:11

Daniel Peñalba