logo codesdope

C# Namespaces


Namespaces are area (or container) which we use to organize our code. Till now, we were using System namespace. In this chapter, we are going to make our own namespace.

We use the namespace keyword to create a namespace. The syntax of making a namespace is:

namespace NameOfNameSpace
{
    //codes
}

We access a member of a namespace using a dot (.) For example, we access the Console class of System namespace using System.Console.

Or we can use using keyword to tell the compiler that we are using a namespace. For example, using NamespaceName.

Let's see an example:

using System;

namespace MyNamespace
{
  class Student
  {
    public static string name = "xyz";
  }
}

class Test
{
  static void Main(string[] args)
  {
    Console.WriteLine(MyNamespace.Student.name);
  }
}
Output
xyz

namespace MyNamespace → We have defined a namespace with a name MyNamesapce.

We have accessed the Student class inside it with Mynamespace.Student.

Let's take an example of using using keyword.

using System;
using MyNamespace;

namespace MyNamespace
{
  class Student
  {
    public static string name = "xyz";
  }
}

class Test
{
  static void Main(string[] args)
  {
    Console.WriteLine(Student.name);
  }
}
Output
xyz

We have written using MyNamespace; at the top of the code. So, we are able to access the Student class without mentioning the name of the namesapce.

Nested Namespace


We can also have one namespace inside another called nested nested namespace. Let's take an example.

using System;

namespace MyNamespace
{
  namespace SecondNamespace
  {
    class Student
    {
      public static string name = "xyz";
    }
  }
}

class Test
{
  static void Main(string[] args)
  {
    Console.WriteLine(MyNamespace.SecondNamespace.Student.name);
  }
}
Output
xyz

Here, we have SecondNamespace inside MyNamespace. We can also use using keyword here.

using System;
using MyNamespace.SecondNamespace;

namespace MyNamespace
{
  namespace SecondNamespace
  {
    class Student
    {
      public static string name = "xyz";
    }
  }
}

class Test
{
  static void Main(string[] args)
  {
    Console.WriteLine(Student.name);
  }
}
Output
xyz

Doubt? Ask question
Close

Welcome.please sign up.

Close

Welcome.please login.