2

Newbie C# question about using & namespaces:

using System;
using System.Data;

namespace Granite2 {
    class Class1 {
        System.Data.SqlClient.SqlConnection Conn1;
        SqlClient.SqlConnection Conn2;
    }
}

Conn1 line, not surprisingly, compiles fine. Conn2 has an error "The type or namespace 'SqlClient' can't be found".

Why is this? I thought having "using System.Data" in there would mean I could reference SqlClient without the full qualifier.

I'm perplexed because I'm converting VB.NET to C# and the namespace works in VB.NET. Obviously some nuance I'm not aware of here.

1
  • 1
    No you need to specify full namespace except for the case above if your class Class1 is in namespace System.Data which is not the case here. Commented Mar 30, 2015 at 12:40

1 Answer 1

1

That's because C# compiler only imports types in namespace you've specified (for your particular case System.Data), but not from all children namespaces of it (so in your case System.Data.SqlClient namespace types were not imported).

As from FAQ of C# team - main reason of doing so is protection against collisions between namespace names.

Just imagine - your namespace X can has children namespaces Y and Z both having SomeClass declared. So if you will using X and then SomeClass с = new SomeClass(); - there will be collision if compiler will import all types from all children namespaces of X.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the reference - there is a comment that VB.NET has the behaviour of importing child namespaces which explains the difference. Although the comment is old, it looks like it's still the case with VB.NET in VS2013

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.