Search code examples
c#usinglanguage-specifications

Why does C# define two different uses for `using`?


More a question out of curiosity than anything, but why does C# define two different "purposes" for the keyword using? On one hand, it's a directive...

used to create an alias for a namespace or to import types defined in other namespaces.

On the other, it's a statement which...

defines a scope, outside of which an object or objects will be disposed.

To me, it seems like different uses for the same keyword, but maybe I'm missing something. Is there a reason why this keyword takes on two different purposes? Or, are both of these purposes, deep down in the belly of the compiler, really the same thing?


Solution

  • I asked Eric Lippert the same question on his blog a few years ago here (see the first comment).

    His response was:

    This is a tricky point of language design; when one keyword is used to represent two completely different concepts, it can be confusing. But introducing a new keyword per concept makes the language feel a bit bloated. I personally would have chosen "imports" or some such syntax for the directive form to ensure that it is not confused with the statement form, but I understand that its a judgment call.

    We were designing a feature for C# 4.0 that got cut which was yet another form of "partial" class; basically, a way to share attribute metadata between the machine-generated and user-generated halves of a partial class. I pushed back on using the keyword "partial" for the feature because we would then have had THREE subtly different meanings for "partial" in C#, which I felt was two too many. (I was advocating adding another conditional keyword "existing". Unfortunately the point ended up moot since the feature was cut for lack of time.) -- Eric

    For those who don't know who Eric is, he's a developer for the C# compiler team.