Why are extension methods only allowed in non-nested, non-generic static class?

Solution 1:

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.

Solution 2:

As Eric Lippert has written many times in his blog, each change to C# is carefully evaluated against a set of criteria to justify it and not based on technology sake alone. In this case, what was not required to enable LINQ was cut off to reduce risk. Check this blog post from Eric for a similar question.

Solution 3:

I believe that this was done so that compiler can locate/search the extension method in reasonable amount of time. Further, note that complier search extension methods only in set of namespaces that are in file scope - this is also done for similar reasons.

If you think about generic static class scenario, compiler must try to instantiate the concrete types for all possible type combinations in order to match the extension method. Even if complier can be smart in doing this, instantiating concrete type for calling extension methods may have side effect that developer may not be aware of.