What are nested namespaces in C#?


A namespace inside a namespace is called a nested namespace in C#. This is mainly done to properly structure your code.

We have an outer namespace −

namespace outer {}

Within that, we have an inner namespace inside the outer namespace −

namespace inner {
   public class innerClass {
      public void display() {
         Console.WriteLine("Inner Namespace");
      }
   }

}

Now to call the method of inner namespace, set a class object of the inner class and call the method as shown in the below example −

namespace outer {
   class Program {
      static void Main(string[] args) {
         innerClass cls = new innerClass();
         Console.WriteLine("Welcome!");
         Program.display();
         cls.display();
         Console.ReadLine();
      }

      public static void display() {
         Console.WriteLine("Outer Namespace");
      }
   }

   namespace inner {
      public class innerClass {
         public void display() {
            Console.WriteLine("Inner Namespace");
         }
      }
   }
}

Updated on: 20-Jun-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements