3

I know we can't have extension method in nested classes and the reasons behind that choice makes perfect sense, I'm not here to talk about this case.

Is there a design reason why it's impossible to have an extension method in a class that is nested in a static class?

public static class MyClass1
{
    public static class MyClass2
    {
        public static int Add(this int a, int b) //Doesn't compile
        {
            return a + b;
        }
    }
}

Is it just because it's a "corner case" that required more work and was considered useless? Or is there another design reason behind this?

IEatBagels
  • 823
  • 2
  • 8
  • 23
  • I was about to flag this as a duplicate of ["*C#: Extension methods not allowed in nested static classes?*"](http://stackoverflow.com/q/772351/1364007) then I reread your question. – Wai Ha Lee Nov 12 '15 at 14:47
  • 3
    How about [this answer by Eric Lippert](http://stackoverflow.com/a/3934737/1364007) to ["*Why are extension methods only allowed in non-nested, non-generic static class?*"](http://stackoverflow.com/q/3930335/1364007). – Wai Ha Lee Nov 12 '15 at 14:49
  • Sounds precisely like the corner case... note that not only the class itself, but all containing classes would have to be non-generic. It could be logically nested in a non-static class though... – Jon Skeet Nov 12 '15 at 14:50
  • I will not add this as an answer because I am unsure about whether it is correct, but i think the main reason behind it could be how the compiler would resolve the scope of the extension methods. Think of collection extensions, which reside in System.Linq. You can only use any meethod, for example, First(), if you have an using directive to that namespace. Though you can't write an using statement like this: using YourRootNameSpace.MyClass1, unless you do this in order to set an alias to it. That is, you will never have MyClass2 directly in scope. – Balázs Nov 12 '15 at 14:50
  • @Balázs: Well, as of C# 6 you can write `using static System.Linq.Enumerable;` - and the rules for how extension methods are found could easily be extended to nested types, anyway. – Jon Skeet Nov 12 '15 at 14:51
  • Previous comment exceeded character limit, so add to it that only being able to use an extension method from within a very limited scope (from inside MyClass1) makes no much sense. – Balázs Nov 12 '15 at 14:51

1 Answers1

2

In this answer, Eric Lippert argues that

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.

He goes on to say that

We considered it carefully for a long time and decided that on the basis of that consideration, the costs of doing the feature (extension methods in nested, generic static class) were not justified by the benefits accrued.

However, you can submit feature requests here.

Community
  • 1
  • 1
Amadeus Sanchez
  • 2,375
  • 2
  • 25
  • 31