A namespace is a C# elements that is used to organized your program and separate the codes. Namespace can contain classes, variable, methods, properties, etc. the main usage of namespace is to avoid conflict between classes that have a similar name. It also provides way to put related object under one name space. Example: the name space System.Text contains all classes and methods related to text operations and manipulation. The name space System.Data is where all Data related classes and methods are housed.

Define a Namespace

In C#, a namespace definition begins with the keyword namespace:

Namespace myNameSpace

{

//code

}

Example of defining a namespace

namespace MyNameSpace
{
 public class MyClass
 {
 public void CreateNamespace()
 {
 System.Console.WriteLine("this is my Namespace");
 }
 }
}

The above namespace contains a class ‘MyClass’ and a void method called ‘CreateNamespace’. Note that you can add more classes to the same namespace. Simply use the same namespace name when you create the class to have it and all its elements added to it.

Access a Namespace object

The object in a name space can be accessed by using the namespace name followed by the dot (.), then the object or member name.

Example of accessing a namespace

MyNameSpace.MyClass classInstance = new MyNameSpace.MyClass();

The code above creates an instant of the class ‘MyClass’, which is a member of the namespace ‘’MyNamespace.

To avoid repeating the namespace name each time you want to access one of its number within a class, use the keyword ‘Using’ at the beginning of that class as the following:

using MyNameSpace;

Now declare an instance of the class MyClass as the following:

MyClass classInstance = new MyClass();

Nested namespace

Nested namespace are one namespace inside another.

Example of nested namespace

// First namespace

namespace MyNamespace1
{
    public MyClass1
    {
        public MyMethod1
    {
            Console.Write(“Class 1”);
        }
    }
}

// Second namespace
namespace MyNamespace2
{
        public MyClass2
    {
            public MyMethod2
    {
                Console.Write(“Class 2”);
            }
        }

    }
}

Use the dot (.) to access the members of the namespace.

Example of accessing a nested namespace

MyNamespace1.MyNamespace2.MyClass2 classInstance = new MyNamespace1.MyNamespace2.MyClass2();
classInstance.MyMethod2();

Namespace Alias

Using nested namespace and other method can lead to a long declaration which can be annoying in a program. A namespace alias is a solution for this problem. Example of namespace alias:

Using MyAlias = MyNamespace1.MyNamespace2.MyNamespace3;

Now use the alias in the program to define an instance of a class:

MyAlias.MyClass classInstance = new MyAlias.MyClass();

 

Last modified: July 28, 2018

Comments

Write a Reply or Comment

Your email address will not be published.