Namespaces - Overview


A namespace is a declarative region. Names declared in one namespace do not conflict with names declared in another. A namespace is declared with the namespace keyword. The syntax for declaring a namespace is shown below.

namespace name
{
     // Members go here
}

An example of declaring a namespace is shown below.

// Namespace1 - A Simple Example

using System;

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

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

A namespace called NameSpace is declared and the class X is declared within this namespace. In Main(), the fully qualified name of the class is used when creating an instance of the class. An instance method is called.

A class declared in one namespace will not conflict with the same class name occuring in another namespace. Each can be referred to by its fully qualified name, as shown in the example below.

// Namespace2 - Non-conflicting Nature of Name Spaces

using System;

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

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

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

        NameSpace2.X y = new NameSpace2.X();
        y.Show();
    }
}

The class X is declared in both NameSpace1 and NameSpace2. There is no conflict in the declaration of the same class in both namespaces. Each class can be referred to by its fully qualified name, as shown in Main() above.