The using Directive
It is possible to import types from one namespace into the enclosing namespace scope. As a result, it would not be necessary for the programmer to fully qualify a type. To achieve this, the C# programmer includes a using directive, generally at the top of the file. For example, in Listing 4.6, Console is not prefixed with System. Instead, it includes the using directive, using System, at the top of the listing.
Listing 4.6. using Directive Example
The results of Listing 4.6 appear in Output 4.2.
A using directive like using System does not enable the omission of System from a method within a more specific namespace. If code accessed a type within System.Text, for example, you would have to either include an additional using directive for System.Text, or fully qualify the type. The using directive does not import any nested namespaces. Nested namespaces, identified by the period in the namespace, need to be imported explicitly.
Typically, prevalent use of types within a particular namespace results in a using directive for that namespace, instead of fully qualifying all types within the namespace. Following this tendency, virtually all files include the using System directive at the top. Throughout the remainder of this book, code listings will often omit the using System directive. Other namespace directives will be included explicitly, however.
One interesting effect of the using System directive is that the string data type can be identified with varying case: String or string. The former version relies on the using System directive and the latter uses the string keyword. Both are valid C# references to the System.String data type, and the resulting CIL code is unaffected by which version is chosen.
The using directive also has a provision for aliasing a namespace or type. An alias is an alternate name that you can use within the scope to which the using directive applies. The two most common reasons for aliasing are to disambiguate two types that have the same name and to abbreviate a long name. In Listing 4.8, for example, the CountDownTimer alias is declared as a means of referring to the type System.Timers.Timer. Simply adding a using System.Timers directive will not sufficiently enable the code to avoid fully qualifying the Timer type. The reason is that System.Threading also includes a type called Timer, and therefore, just using Timer within the code will be ambiguous.
Listing 4.8. Declaring a Type Alias
Listing 4.8 uses an entirely new name, CountDownTimer, as the alias. It is possible, however, to specify the alias as Timer, as shown in Listing 4.9.
Listing 4.9. Declaring a Type Alias with the Same Name
Because of the alias directive, "Timer" is not an ambiguous reference. Furthermore, to refer to the System.Threading.Timer type, you will have to either qualify the type or define a different alias.