Thursday, May 23, 2013

Namespace in C#


Concept of Namespace

What is Namespace:-

Namespaces is logical building blog of C# assembly. We can compare namespace like package of java. Something similar, But not exact. Basically namespace are used to avoid collision problem. In my below example I have define same class in my same assembly. But I have kept those two classes in two different namespace.

namespace Namespace1
{
    class MyClass
    {
        public void Hello()
        {
            Console.Write("I am hello within Namespace 1");
        }
    }
}

namespace Namespace2
{
    class MyClass
    {
        public void Hello()
        {
            Console.Write("I am hello within Namespace 2");
        }
    }
}

  • Namespace1
  • Namespace2


Now ,Your problem has solved. In real time project there might be same class name in same DLL or assembly. And you can easily avoid name collision problem by putting them in different assembly.
And when you like to call Hello() function which belongs to Namespace1 ,Just use full path of Class and create object of particular class. And use this object to call your function. like
Namespace1.MyClass objC = new Namespace1.MyClass();
objC.Hello();

Here I have given full code.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Namespace1
{
    class MyClass
    {
        public void Hello()
        {
            Console.Write("I am hello within Namespace 1");
        }
    }
}

namespace Namespace2
{
    class MyClass
    {
        public void Hello()
        {
            Console.Write("I am hello within Namespace 2");
        }
    }
}
namespace BlogProject
{
    class Program
    {
        static void Main(string[] args)
        {
            Namespace1.MyClass objC = new Namespace1.MyClass();
            objC.Hello();
            Console.ReadLine();
        }
    }
}


No comments:

Post a Comment