Search code examples
c#language-design

Why did the C# designers attach three different meanings to the 'using' keyword?


The using keyword has three disparate meanings:

  1. type/namespace aliasing
  2. namespace import
  3. syntactic sugar for ensuring Dispose is called

The documentation calls the first two definitions directives (which I'm guessing means they are preprocessing in nature), while the last is a statement.

Regardless of the fact that they are distinguished by their syntaxes, why would the language developers complicate the semantics of the keyword by attaching three different meanings to it? For example, (disclaimer: off the top of my head, there may certainly be better examples) why not add keywords like alias and import? Technical, theoretical, or historical reasons? Keyword quota? ;-)

Contrived sample:

import System.Timers;
alias LiteTimer=System.Threading.Timer;
alias WinForms=System.Windows.Forms;

public class Sample {
  public void Action() {
    var elapsed = false;
    using(var t = new LiteTimer.Timer(_ => elapsed = true) {
      while (!elapsed) CallSomeFinickyApi();
    }
  }
}

"Using" is such a vague word.


Solution

  • It's a jugdment call. I personally would have made the choice you suggest: use something like "alias" and "import". I note that "alias" is a contextual keyword of C# and is used to declare that an extern alias is in usage in a particular file; it seems more natural to use that for declaring a type alias instead of "using".

    The statement form of "using" was actually added rather late in the game; the designers wished to use "using" not just because it is already a keyword, but also because it emphasizes that a resource is being used in a particular region of code and is then going away. The fact that "using" already had a meaning in the directive sense was a happy accident.

    If this topic interests you, I've written several articles on it. Here for instance I have articles on how "fixed", "partial" and "into" also have multiple meanings in C#:

    http://blogs.msdn.com/ericlippert/archive/tags/What_2700_s+The+Difference_3F00_/default.aspx

    Another answer also links to my article discussing how we ensure that not too many words are reserved for use by the language:

    http://ericlippert.com/2009/05/11/reserved-and-contextual-keywords/