Nested Namespaces


A namespace can be nested within another namespace. The next example does this.

// Namespace6 - Nested Namespaces

using System;
using NameSpace;

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

    namespace Nested
    {
        class Y
        {
            public void Show()
            {
                Console.WriteLine("In y.Show in NameSpace.Nested");
            }
        }
    }
}

class Program
{
    static void Main()
    {
        X x = new X();
        x.Show();

        NameSpace.Nested.Y y = new NameSpace.Nested.Y();
        y.Show();
    }
}

Within namespace NameSpace is nested another namespace called Nested. The class Y is declared in NameSpace.Nested. In Main(), X is used unqualified (re: using directive), but Y is instantiated using its fully qualified name NameSpace.Nested.Y. The using directive:

using NameSpace.Nested;

near the top of the program would have meant that Y could have been used unqualified.

A nested namespace may be specified with a single namespace statement by separating each namespace with a period. For example

namespace Outer
{
  namespace Inner
  {
    // ...
  }
}

can be replaced with the following.

namespace Outer.Inner
{
  // ...

}