Casebash
Casebash

Reputation: 118862

Why do standard libraries for C# need both an assembly reference and an import?

What is the reason that I have to do both of these for the standard libraries? For every other language that I have used, I only have to do one to access standard libraries.

Upvotes: 0

Views: 416

Answers (4)

R. Martinho Fernandes
R. Martinho Fernandes

Reputation: 234514

Assembly references are a concept of the platform, while a namespace import is a concept of the language.

You need to give an assembly reference to the compiler because it needs to know where the library code you're using is. But the using directive is purely optional. Both these will compile fine:

Example 1:

System.Console.WriteLine("Without a using directive");

Example 2:

using System;
//...
Console.WriteLine("With a using directive");

The using directive serves only to save you from having to write fully qualified names all over the place.

Upvotes: 2

Kirk Woll
Kirk Woll

Reputation: 77556

An assembly reference makes the code in the assembly available to another assembly. A using directive makes the types of another namespace available to a given source file. These are completely separate concepts. If you were inclined, you could get away with never using the usings directive and using fully-qualified type names. Similarly, it is possible to use the usings directive to refer to other namespaces within the same assembly.

Also, there is a perfect analog between assemblies/jars and usings/import between Java and C# for the purposes of this discussion. So C# is hardly unique here.

Upvotes: 9

Brian Rasmussen
Brian Rasmussen

Reputation: 116411

You need to reference the assemblies to let the compiler know where to locate the types they export. You don't need to include namespaces, but it makes code easier to read as you can avoid fully qualified names. Additionally since each assembly may expose several namespaces it is a convenient way to group related types.

Upvotes: 1

Marco
Marco

Reputation: 1346

Visual studio needs certain attributes of a reference to decide how to resolve it at runtime and how to deploy it when building the project. These options cannot be implied by a simple import statement.

Upvotes: 1

Related Questions