Resolving Namespace Conflicts in C#

 

A nested namespace may have an identifier name that conflicts with the global namespace. For example, a company, Co, has developed several in-house classes, such as OurList, that are logically grouped under its own System.Collections namespace. An application App would like to use the ArrayList class from the .NET System.Collections namespace and the OurList class from the nested Systems.Collections namespace. Unfortunately, the Co.System.Collections namespace hides access to the .NET System.Collections and generates a compilation error as shown below.

 

using SC = System.Collections; // To access ArrayList class.

 

namespace Co

{

    namespace System

    {

        namespace Collections

        {

            public class OurList { /* ... */ }

            // ...

        }

    }

    namespace Project

    {

        public class App

        {

            // ...

            private System.Collections.ArrayList a; // Compilation error.

            private System.Collections.OurList o;

        }

    }

}

 

The error in this example can be removed if the global namespace qualifier :: is used instead. This qualifier tells the compiler to begin its search at the global namespace. Since the .NET System is rooted at the global namespace, replacing System.Collections by its alias SC:: enables access to the ArrayList class in the .NET namespace System.Collections as shown below.

 

private SC::ArrayList a;