What does the using directive do, exactly?
Asked Answered
E

4

7

On MSDN I can read what it does, but I would like to know what it does technically (tells compiler where to look for types..)? I mean using as a directive.

Eloquent answered 21/10, 2010 at 20:47 Comment(0)
S
10

The primary function of the using directive is to make types within a namespace available without qualification to the user code. It considers the set of namespaces and types which are defined in referenced assemblies and the project being compiled.

Take for example the following definition in MyTypes.Dll

namespace MyTypes {
  class Class1 {}
}

Now consider referencing MyTypes.dll from another project with a different namespace. Without a using directive to create Class1 i need to qualify the name

MyTypes.Class1 local1 = new MyTypes.Class1();

The using directive lets me remove this qualification

using MyTypes;
...
Class1 local1 = new Class1();
Stroke answered 21/10, 2010 at 20:53 Comment(2)
also, if the type is not found within the app namespace, compiler will search through namespaces included by using, right?Eloquent
@Mojmi for the common case yes. Name lookup is actually quite complex and i specifically didn't comment on exactly how it works due to the high likelyhood that I would get the fun details wrong.Stroke
D
3

@JaredPar's answer is correct, however I'd like to add that it doesn't quite work the same way as say import in Java. (someone correct me if I'm wrong about Java's import actually importing it into memory)

You need to include either a DLL or project reference in order to even be able to use using however it's not loaded into memory until you actually call into a method/property/something in the assembly. So you could have using System.Linq; but if you don't actually use any Linq methods, the Linq assembly is never loaded. (I'm not 100% positive that Linq is in it's own physical assembly since namespaces and assemblies aren't 1:1, but for sake of example I'm assuming it is)

Diaphane answered 21/10, 2010 at 21:1 Comment(0)
D
0

using informs the compiler which namespaces to search for names used in the file but not defined in the file.

Disinclination answered 21/10, 2010 at 20:52 Comment(0)
A
-1

using just tell the compiler to go to the assembly's configuration file and search for a specific DLL with the name given, if the DLL is found then it links that dll into the current project. using is just a link operation to have DLL talk to each other in a shared space in memory. The guy below here is right

Androclinium answered 21/10, 2010 at 21:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.