Share via


How to: Use the Global Namespace Alias (C# Programming Guide)

The ability to access a member in the global namespace is useful when the member might be hidden by another entity of the same name.

For example, in the following code, Console resolves to TestApp.Console instead of to the Console type in the System namespace.

using System;
class TestApp
{
    // Define a new class called 'System' to cause problems. 
    public class System { }

    // Define a constant called 'Console' to cause more problems. 
    const int Console = 7;
    const int number = 66;

    static void Main()
    {
        // The following line causes an error. It accesses TestApp.Console, 
        // which is a constant. 
        //Console.WriteLine(number);
    }
}

Using System.Console still results in an error because the System namespace is hidden by the class TestApp.System:

// The following line causes an error. It accesses TestApp.System, 
// which does not have a Console.WriteLine method.
System.Console.WriteLine(number);

However, you can work around this error by using global::System.Console, like this:

// OK
global::System.Console.WriteLine(number);

When the left identifier is global, the search for the right identifier starts at the global namespace. For example, the following declaration is referencing TestApp as a member of the global space.

class TestClass : global::TestApp

Obviously, creating your own namespaces called System is not recommended, and it is unlikely you will encounter any code in which this has happened. However, in larger projects, it is a very real possibility that namespace duplication may occur in one form or another. In these situations, the global namespace qualifier is your guarantee that you can specify the root namespace.

Example

In this example, the namespace System is used to include the class TestClass therefore, global::System.Console must be used to reference the System.Console class, which is hidden by the System namespace. Also, the alias colAlias is used to refer to the namespace System.Collections; therefore, the instance of a System.Collections.Hashtable was created using this alias instead of the namespace.

using colAlias = System.Collections;
namespace System
{
    class TestClass
    {
        static void Main()
        {
            // Searching the alias:
            colAlias::Hashtable test = new colAlias::Hashtable();

            // Add items to the table.
            test.Add("A", "1");
            test.Add("B", "2");
            test.Add("C", "3");

            foreach (string name in test.Keys)
            {
                // Searching the global namespace:
                global::System.Console.WriteLine(name + " " + test[name]);
            }
        }
    }
}
A 1
B 2
C 3

See Also

Reference

Namespaces (C# Programming Guide)

. Operator (C# Reference)

:: Operator (C# Reference)

extern (C# Reference)

Concepts

C# Programming Guide