What is a Namespace in C#?

C#This is very basic and general question, which comes in mind of every student who wants to start learning C# programming.  I was a bit confused over this concept, but later I figured it out.  If you want to build a C# application, then you must understand that namespaces are very very important.  Let me explain you this by a very common example.  Suppose there are 2 cricket teams, Team A and Team B.  Like every cricket team, they have bunch of players with a different skills set.  In C# programming language, you can consider those teams as 2 different namespaces with bunch of different type of members like enums, delegates, structs, classes etc.

You must remember this, a namespace can contain:

  1. Another namespace
  2. Class
  3. Delegate
  4. Enum
  5. Interface
  6. Struct

During building our application, we have to make use of many classes, interfaces, enums, delegates etc.  To access these members, we can make use of their fully qualified name.  Fully qualified name basically means exact location of that specific member, where it is actually declared.  To make things easy for you, lets go with an example.  To write and read on a console window, we make use of Console class and Console class resides in System namespace.  Now, if we want to type the fully qualified name of this, then that would be System.Console.WriteLine or System.Console.ReadLine

It is very common a namespace can contain many classes and typing fully qualified name again and again will be time consuming.  To overcome this lengthy process of typing, we can use using keyword at top of our code file.  Example is given below.

Before

namespace HelloProject
{
    class Program
    {
        static void Main(string[] args)
        {
           System.Console.WriteLine("Hello World");
        }
    }
}

After

using System;

namespace HelloProject
{
    class Program
    {
        static void Main(string[] args)
        {
           Console.WriteLine("Hello World");
        }
    }
}

Considering the above scenario, now we know that it is not necessary to use fully qualified name.  But if 2 namespaces contain a member with same name, you have to use fully qualified name, just to avoid any ambiguity.  Now, in this situation, we again encounter a lengthy name, which we have to use throughout the code.  In this case, we will use alias directives.  Alias directives are basically a short name, which you will assign to fully qualified name of namespace and use its classes throughout the coding process.  Example is given below.

using System;
using Alias1 = System.Configuration;
using Alias2 = System.ComponentModel;

namespace HelloProject
{
    class Program
    {
        static void Main(string[] args)
        {
           Console.WriteLine("Hello World");
        }
    }
}