#988 – Using global to Explicitly Refer to a Namespace

A fully qualified namespace is not always sufficient to refer to a type.  Below, we’ve (unwisely) declared two different classes named Utility–a subclass of Program in the ConsoleApplication1 namespace and a class in the Program namespace.

If we refer to Program.Utility from within the Main method, the subclass is used.  To use the other version of Utility, we need to use the global keyword to describe the exact path to the type.  global::Program refers to the top-level namespace Program.

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            // Class Program.Utility in namespace ConsoleApplication1
            Program.Utility util = new Program.Utility();

            // Class Utility in namespace Program
            global::Program.Utility util2 = new global::Program.Utility();
        }

        class Utility
        {
            public Utility()
            {
                Trace.WriteLine("Class Program.Utility in namespace ConsoleApplication1");
            }
        }
    }

}

namespace Program
{
    public class Utility
    {
        public Utility()
        {
            Trace.WriteLine("Class Utility in namespace Program");
        }
    }
}
Advertisement

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

One Response to #988 – Using global to Explicitly Refer to a Namespace

  1. Pingback: Dew Drop – December 4, 2013 (#1676) | Morning Dew

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: