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

I understand that C # extension methods must be static. I don’t understand why these extensions cannot be defined in non-stationary classes or general ones?

Update: I'm interested in the reason for this design decision.

+7
source share
3 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 to the method call. This first argument is "this" and is executed implicitly.

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

Is it possible that method resolution will be confused if you can define extension methods and instance methods in the same class, that is, define methods with the same name and essentially the same parameters when the "this" parameter is enabled.

+5
source

Take a look at this part of the .NET C # specification:

When the first parameter of a method includes this modifier, this method is called an extension method. Extension methods can be declared in non-generic, non-nested static classes. The first parameter of the extension method cannot have any modifiers except this, and the type of the parameter cannot be the type of a pointer.

And this snippet from Jon Skeet answer :

I don’t understand why all these restrictions are necessary - except potentially for the simplicity of the compiler (and language). I can understand why it makes sense to limit it to non-generic types, but I cannot immediately understand why they should be non-nested and static. I suspect that search rules are much simpler if you do not have to worry about the types contained in the current type, etc., but I dare say that this is possible.

+3
source

Because the specification says so ... Now, probably, there are good reasons why they wrote the specification in this way.

The reason they cannot be declared in generic classes is quite obvious: given the way you call extension methods, where would you specify the type argument for the class?

The reason why this should be a static class is less obvious, but I think it makes sense. The main use case for static classes is to combine helper methods together (e.g. Path , Directory , ProtectedData ...), and extension methods are mostly helper methods. It would be pointless to create an instance of Enumerable or Queryable , for example.

+1
source

All Articles