Namespace Aliases


When two namespaces are brought into view via using, if both contain class X, any reference to X alone will be ambiguous. For example, consider the following program which doesn't compile because of an ambiguous reference.

// Namespace7 - Ambiguous Reference
//            - Doesn't Compile

using System;
using NameSpace1;
using NameSpace2;

namespace NameSpace1
{
    class X
    {
        public void Show()
        {
            Console.WriteLine("In X.Show in NameSpace1");
        }
    }
}

namespace NameSpace2
{
    class X
    {
        public void Show()
        {
            Console.WriteLine("In X.Show in NameSpace2");
        }
    }
}


class Program
{
    static void Main()
    {
        X x = new X(); // Ambiguous Reference
        x.Show();
    }
}

The class X occurs both namespaces NameSpace1 and NameSpace2. Both the namespaces have been brought into view. In Main(), an attempt is made to reference X without qualification. As the comment implies, the compiler flags the line as an error.

The :: operator is the namespace alias qualifier. It ties an entity to the associated namespace and can thus resolve ambiguities. The syntax for the operator is as follows.

namespace-alias::identifier

namespace-alias is the name of a namespace alias and identifier is the name of a member of that namespace.

The ambiguity in the previous program is resolved using the namespace alias qualifier in the next example.

// Namespace8 - Alias Qualification

using System;
using NameSpace1;
using NameSpace2;

using Alias1 = NameSpace1;
using Alias2 = NameSpace2;

class X // X in Global Namespace
{
    public void Show()
    {
        Console.WriteLine("In X.Show in Global Namespace");
    }
}

namespace NameSpace1
{
    class X
    {
        public void Show()
        {
            Console.WriteLine("In X.Show in NameSpace1");
        }
    }
}

namespace NameSpace2
{
    class X
    {
        public void Show()
        {
            Console.WriteLine("In X.Show in NameSpace2");
        }
    }
}


class Program
{
    static void Main()
    {
        Alias1::X x = new Alias1::X(); // Alias selects NameSpace1
        x.Show();

        Alias2::X y = new Alias2::X(); // Alias selects NameSpace2
        y.Show();

        global::X z = new global::X(); // Alias selects Global Namespace
        z.Show();
    }
}

A global version of X exists and two versions in two different namespaces. Aliases are formed for the containing namespaces and Main() uses these aliases (together with the alias global) to select specific versions of X. The output of the program is shown below.

In X.Show in NameSpace1
In X.Show in NameSpace2
In X.Show in Global Namespace