using Directive Not Importing as Expected

  • Thread starter Thread starter Jeff S
  • Start date Start date
J

Jeff S

I have the following three lines at the very top of a class file (prior to
the namespace declaration line).

using System;
using System.Data;
using System.Data.SqlClient;

Then, in a subsequent function in the same file I want to create a
connection by entering the following line:
SqlClient.SqlConnection cn = new
SqlClient.SqlConnection(Constants.ConnectionString);

However, as I start to enter that line, Intellisense does not recognize
SqlClient, and I must specify the fully qualified namespace hierarchy as
follows:

System.Data.SqlClient.SqlConnection cn = new
System.Data.SqlClient.SqlConnection(Constants.ConnectionString);

I thought that specifying 'using System.Data;' and 'using
System.Data.SqlClient' would be enough to import those namespaces. What am I
missing?

Thanks,

Jeff
 
SqlClient.SqlConnection cn = new
SqlClient.SqlConnection(Constants.ConnectionString);

There's no need to type SqlClient. Try:
SqlConnection cn = new SqlConnection(Constants.ConnectionString);
 
Jeff S said:
I have the following three lines at the very top of a class file (prior to
the namespace declaration line).

using System;
using System.Data;
using System.Data.SqlClient;

Then, in a subsequent function in the same file I want to create a
connection by entering the following line:
SqlClient.SqlConnection cn = new
SqlClient.SqlConnection(Constants.ConnectionString);

However, as I start to enter that line, Intellisense does not recognize
SqlClient, and I must specify the fully qualified namespace hierarchy as
follows:

System.Data.SqlClient.SqlConnection cn = new
System.Data.SqlClient.SqlConnection(Constants.ConnectionString);

I thought that specifying 'using System.Data;' and 'using
System.Data.SqlClient' would be enough to import those namespaces. What am I
missing?

Short answer: just write SqlConnection.

Long answer: unlike C++, in C# only unqualified names (without '.') are searched
in imported namespaces. Qualified names must always start from root. There is no such
thing as "partially qualified name".

Ivan
 
Back
Top