C Sharp

The System.Console.WriteLine Method

The System.Console.WriteLine method writes the provided string-followed by a line terminator-to the standard output device. In most cases, unless you do something fancy to change this or are using an editor that redirects the output to a window, this means the string will be output in a console window.

Namespaces and the using Directive

In Chapter 2, "Introducing Microsoft .NET," you learned that the .NET Framework class library is organized into a hierarchical lattice of namespaces. This can result in some rather lengthy names when a desired class or type is nested several layers deep. Therefore, to save on typing, C# provides the using directive. Let's look at an example of how this directive works. In our "Hello, World" application, we have the following line of code: -

    System.Console.WriteLine("Hello, World");

Typing this once isn't such a big deal, but imagine having to fully qualify every type or class in a large application. The using directive gives you the ability to list a kind of search path so that if the compiler can't understand something you've typed, it will search the listed namespaces for the definition. When we incorporate the using directive into our example, it looks like this: -

using System;
class HelloWorld
{
    public static void Main()
    {
        Console.WriteLine("Hello, World");
    }
}

When the compiler parses the Console.WriteLine method, it will determine that the method is undefined. However, it will then search through the namespaces specified with the using directives and, upon finding the method in the System namespace, will compile the code without error.

Note that the using directive applies to namespaces and not classes. In the example we're using, System is the namespace, Console is the class, and WriteLine is a static method belonging to Console. Therefore, the following code would be invalid: -

using System.Console; //ERROR Can't use a using
                      //directive with a class.
class HelloWorld
{
    public static void Main()
    {
        WriteLine("Hello, World");
    }
}

Although you can't specify a class in a using directive, the following variant of the using directive does enable you to create aliases for classes: -

using alias = class -

Using this form of the using directive, you can write code like the following: -

using ouput = System.Console;
class HelloWorld
{
    public static void Main()
    {
        output.WriteLine("Hello, World");
    }
}

This gives you the flexibility to apply meaningful aliases to classes that are nested several layers deep in the .NET hierarchy, thus making your code a little easier to both write and maintain.

by BrainBellupdated
Advertisement: