Why are extension methods only allowed in non-nested, non-generic static class? Is it useless to consider extension methods in nested, generic static class?
Actually I'm answering the question of why extension methods cannot work with static classes. The answer is because extension methods are compiled into static methods that cannot recieve a reference to a static class.
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.
Extension methods are static because they get the instance passed in via the first parameter, and they don't act on the actual instance of their declaring class. Also, they're just a syntactic sugar. CLR doesn't support such a thing.
Yes. It is compulsion that the Extension method must be in a Static class only so that only one Instance is created.
Why are extension methods only allowed in non-nested, non-generic static class?
As Pratik points out, the question we face is not "why are extension methods not allowed in nested or generic classes?" The question we face as language designers is "why should extension methods be allowed in nested or generic classes?"
Unless the feature is justified by some real-world user need, we're not going to take on the considerable costs of designing, implementing, testing, documenting and maintaining the feature.
Basically, extension methods were designed to make LINQ work. Anything that didn't contribute to making LINQ work was cut. LINQ only needs extension methods in static, non-generic, non-nested classes to work, so that's what we designed and implemented.
If you have a scenario where extension methods would be useful in non-static, generic, or nested classes then I'm happy to take a look at the scenario. The more real-world scenarios we get, the more likely it is that we'll make a feature in some hypothetical future language that benefits those scenarios.
Is it useless to consider extension methods in nested, generic static class?
No, it is a great idea to consider it. We would be remiss in our duties if we did not consider it. We considered it carefully for a long time and decided that on the basis of that consideration, the costs of doing the feature were not justified by the benefits accrued.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With