Tanzim Saqib on .NET discovery

January 2, 2008

Namespace Alias Qualifier – to get rid of crazy coding

Filed under: C# — tanzimsaqib @ 1:00 am

Let us say somebody in your company loves crazy coding and really do not bother about his/her codes affect others. (S)He put class name System and a constant Console and now wondering how come a simple Console.WriteLine does not compile:

class System
{
    int Console = 10;

    static void Main(string[] args)
    {
        Console.WriteLine("Hello World!"); // Compile time error
        System.Console.WriteLine("Hello World!"); // Compile time error
    }
}

Making use of global::System.Console must solve your problem:

class System
{
    int Console = 10;

    static void Main(string[] args)
    {
        global::System.Console.WriteLine("Hello World!");
        global::System.Console.WriteLine("Hello World!");
    }
}

However, ever thought of a scenario where there can be same class name under two different namespaces? Here comes the role of Namespace Alias Qualifier. In namespace declaration by “using”, aliases can be assigned to namespaces so that they might be useful in later part of the code as shorthand and most importantly will solve the problem of ambiguity:

using sys = System;
using mine = MyProject.Process;
...
...
sys.Console.WriteLine(mine.Console["width"]);

No Comments Yet »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a comment

Blog at WordPress.com.