Information Technology Reference
In-Depth Information
The using Directives
Fully qualified names can be quite long, and using them throughout the code could become
quite tedious. There are two compiler directives, however, that allow you to avoid having to use
fully qualified names—the using namespace directive and the using alias directive .
Two important points about the using directives are the following:
￿
They must be placed at the top of the source file, before any type declarations .
￿
They apply for all the namespaces in the current source file.
The using Namespace Directive
You saw in the MyWidgets example several sections back that you can specify a class by using
the fully qualified name. You can avoid having to use the long name by placing using
namespace directives at the top of the source file.
The using namespace directive instructs the compiler that you will be using classes from
certain specific namespaces. You can then use the simple class names without having to fully
qualify them.
When the compiler encounters a name that is not in the current namespace, it checks the
list of namespaces given in the using namespace directives and appends the unknown name
to the first namespace in the list. If the resulting fully qualified name matches a class in this
assembly or a referenced assembly, the compiler uses that class. If it does not match, it tries the
next namespace in the list.
The using namespace directive consists of the keyword using , followed by a namespace
identifier.
Keyword
using System ;
Name of namespace
One method I have been using throughout the text is the WriteLine method, which is a
member of class Console , in the System namespace. Rather than use its fully qualified name
throughout the code, I simplified our work just a bit, by the use of the using namespace direc-
tive at the top of the code.
For example, the following code uses the using namespace directive in the first line to state
that the code uses classes or other types from the System namespace.
using System; // using namespace directive
...
System.Console.WriteLine("This is text 1"); // Use fully qualified name.
Console.WriteLine("This is text 2"); // Use directive.
Search WWH ::




Custom Search