ASP.NET, Coding

How to use Namespace Alias Qualifier – (global)

Suppose you define a namespace TestModule and also define a class with the same name inside it as shown in the example below:

namespace TestModule
{  
    class TestClass
    {
        class TestModule { }
        TestModule.TestClass test = new TestModule.TestClass(); 
    } 
}

When you try to instantiate “TestClass” qualified with the namespace name “TestModule”, the compiler will give an error saying: “The type name ‘TestClass’ does not exist in the type ‘TestModule.TestClass.TestModule’”. This happens because the class “TestModule” which is inside hides the namespace “TestModule” which is at the global level.

The external alias global(C#)/Global(VB.NET) can be used to resolve conflicts between namespaces and hiding inner types as shown below:

namespace TestModule
{  
    class TestClass
    {
        class TestModule { }
        global::TestModule.TestClass test = new global::TestModule.TestClass(); 
    } 
}

When the “global” alias is used, the search for the right-side identifier starts at the global namespace which is the root level of the namespace hierarchy. This helps to resolve the type from the outer most level (global level) drilling inwards.

The chances for such conflicts can be avoided to a good extent by following proper naming standards. But when huge class libraries and third-party components are used this situation can arise. In such cases the usage of namespace alias qualifier can save a lot of time!!

You Might Also Like