views:

42

answers:

4

If you have

using XXXX.YYYY;

at the top of a C# file, do you need to include that assembly in the References part of the project?

What is the difference?

A: 

You don't write using XXXX.dll at the top of a CS File.

I believe you're referring to using NamespaceX; which is a way of categorizing your classes into distinct logical partitions. So I'd group all of my Data Access classes into a namespace called MyProject.DataAccess. An assembly can contain classes belonging to multiple namespaces.

In which case, you need to reference the assembly X if you want to use some types/classes defined in assembly X with that namespace.

Gishu
A: 

The using statement states you want to import a namespace into the file, giving you shorthand access. For example you can write File.Delete(file) instead of System.Io.File.Delete(file) if you imported the System.Io namespace. The namespace you are including should be available in one of your references assemblies. As fasr as I know, you can't reference DLL's directly like that from your code.

Robert Massa
A: 

The "using" keyword is a way of avoiding having to type out the whole namespace for a class every time if it lives outside the current namespace.

For example, if I have namespace foo and I want to reference MyClass in namespace bar I can either write:

bar.MyClass = new bar.MyClass();

or

using bar;
...
MyClass = new MyClass();

The references part of the project tells the compiler which libraries outside the current project to search for the class bar.MyClass

So in short you don't need to put the using statement (but it generally makes the code easier to read and less for you to type) but you do need the referenced assembly.

Paolo
OK, but it is bit confusing when the referenced assemblies also have dots in the names. Why doesn't the compiler just use the "using XXX.YYY;" like other compilers do? It seems like I am doubling up on references.
Craig Johnston
Because the namespaces within an assembly don't have to match the assembly name, it's just a convention not a compiler-enforced rule. Also multiple versions of an assembly can use the same namespace (think NUnit or the MS Logging components) so you need to tell the compiler which version you are referencing.
Paolo
+1  A: 

The references are needed to be added, so that they may be physically located by the compiler at compile time.

For more details watch it at http://en.csharp-online.net/CSharp_FAQ:_Why_add_a_using_statement_and_a_reference

Hope this helps.

Thanks,

Madhup

Madhup