C# Language Design – Why Does C# Not Allow Scope-Local Using Directive

chistorylanguage-design

One thing I do not get with C#'s using Directive is why I can only "use" a namespace at file level, and not within any arbitrary block scope.

(using namespace x; of C++ does allow this and certainly the C# designers where aware of this.)

If I have, e.g., one single function in my class that does something with file I/O, it seems to me it would make sense to just write:

void MunchFile(string name) {
  using System.IO; // not allowed
  ...
}

but instead I have to write:

// somewhere at the top of the file:
using System.IO;
... 2 pages down ...
    void MunchFile(string name) {
      ...
    }

It's an irritation every time I encounter it and I keep scratching my head why this was not allowed / implemented.

So:

  • Are there any statements by C# designers wrt. this?
  • Is there any conceptual language design issue wrt. this?

Best Answer

While he doesn't refer specifically to the using directive, Eric Gunnerson's article Minus 100 Points addresses the general question of "why doesn't C# have [feature X] which C++ has". The most relevant part reads:

That wording implies that we started with an existing language (C++ and Java are the popular choices here), and then started removing features until we got to a point where we liked. And, though it may be hard for some to believe, that’s not how the language got designed.

One of the big reasons we didn’t do this is that it’s really hard to remove complexity when you take a subtractive approach, as removing a feature in one area may not allow you to revisit low-level design decisions, nor will it allow you to remove complexity elsewhere, in places where it support the now-removed feature.

So, we decided on the additive approach instead, and worked hard to keep the complexity down.

He goes on to describe how the importance of a feature can be weighed against the complexity it introduces. Long story short, a lot of features that other languages have didn't make the cut, because the results they achieve simply aren't compelling enough for a language whose designers were aiming at simplicity.

Related Topic