What is NameSpace in .Net

This a basic question which allways asked in the interview that what is the namespace ,do you know about namespace,can you tell me some words about namespace.

NameSpace is the Logical group of types or we can say namespace is a container (e.g Class, Structures, Interfaces, Enumerations, Delegates etc.), example System.IO logically groups input output related features , System.Data.SqlClient is the logical group of ado.net Connectivity with Sql server related features. In Object Oriented world, many times it is possible that programmers will use the same class name, Qualifying NameSpace with class name can avoid this collision.

Example :-
// Namespace Declaration
using System;


// The Namespace
namespace MyNameSpace
{
    // Program start class
    class MyClass
    {
        //Functionality

    }

}

Namespaces allow you to create a system to organize your code. A good way to organize your namespaces is via a hierarchical system. You put the more general names at the top of the hierarchy and get more specific as you go down. This hierarchical system can be represented by nested namespaces. Bellow shows how to create a nested namespace. By placing code in different sub-namespaces, you can keep your code organized.

// Namespace Declaration
using System;

// The Namespaces
namespace MyNameSpace
{
    namespace Video
    {
        // Program start class
        class MyVideo
        {
            //Functionality
            public static void play()
            {
                //..
            }
        }
    }

    namespace Audio
    {
        // Program start class
        class MyAudio
        {
            //Functionality

            public static void play()
            {
                //..
            }
        }
    }
}

Now a question arise on our mind that how to call the namespace members, so there is two way to call namespace members -
  • By implementing fully qualified name inline 
  • By implementing the using directive.
Here i am providing an example of how to call namespace members with fully qualified names.

A fully qualified name contains every element from the namespace name down to the method call.
In the above example there is a nested namespace tutorial within the "MyNameSpace" namespace with class "MyVideo", "MyAudio" and method play().

Here we call this method with the fully qualified name :

public void call()

{
    MyNameSpace.Video.MyVideo.play() 
    MyNameSpace.Audio.MyAudio.play()
}


Now implement namespaces by using directive

using MyNameSpace.Video;
using MynameSpace.Audio;


public void call()
{
  MyVideo.play()
}

If we call "play" method in the same namespace then no need to include "MyNameSpace" at the begin
MyVideo.play()  // calling in the same name space


If our method would not be static then make instance then call by the object of the class.

Popular Posts