Why does “using” only import types, not namespaces?


Given a type named:

System.Data.SqlClient.SqlConnection

The following works:

using System.Data.SqlClient;

         SqlConnection connection;

But this is an error:

using System.Data;

         SqlClient.SqlConnection connection;

Why?

Well, the rule is that C# only imports the types in the namespace mentioned in the “using” statement.

Back in the early days of C#, we had a slightly different rule, which I *think* also imported namespaces as well as types, but with that behavior, users were getting into situations where they had name collisions and were having difficulty figuring out what was going on (and, perhaps, coming up with workarounds – we obviously didn’t have the global namespace operator coming in Whidbey), so we decided to limit the number of things that go into the global namespace.

Comments (9)

  1. Daniel Moth says:

    IMO, this is actually one of the few things that are nicer in VB

  2. Frisky says:

    I have not seen Whidbey, but, I like the namespace decision. It is really easy to manage. Ok, you have to type a little, but it is easy to track objects back to their source.

    Would be nice if when you reference a new item like a SortedList, that it would add the using clause for you. If it can’t resolve it because of name clashes, let it prompt me with a list and let me choose. (Perhaps that is in Whidbey.)

  3. Frisky: that’s one of the refactoring features of VS2005. When you type a type name that has not yet been referenced, a smart tag appears and you can choose from a list of namespaces that contain this type name to quasi-automatically add the relevant using statement to the top of the file.

  4. Kevin Daly says:

    I remember being perplexed the first time I had a good look at a serious VB.NET program (owing to the different behaviour), and I suspect VB.NET programmers have it on their list of reasons why they don’t like C#, but I do get the point about name collisions.

    Oddly enough, the only time I’m normally bothered is when using a certain part of the System.Configuration namespace (which I won’t specify, just to be annoying)

  5. SuperJason says:

    This explains the "using" confusion I’ve had since I switched to c#. I’m not sure if I like it.

  6. cashless says:

    Why not allow something like a wild card?

    using System.Configuration.*

    using System.Data.*

  7. Eric says:

    Cashless,

    The simple answer is that the functionality wouldn’t be worth the complexity.

    Eric