Namespaces in C#

Namespaces in C# are used to package different classes with similar functionality. For instance, parent and child classes can be stored in the same namespace. If you look at the top of your code you see a statement using System; Here system is a namespace that contains different classes that contains system specific functionalities. For instance the Console class is a class within System namespace and it is used to display data on the console window.

You can create your own namespace using keyword namespace. Also, you can package as many classes within a namespace as you want. Have a look at the following example to see how namespaces are defined in C#.

´╗┐using System;
namespace Namespace1 {
    public class Class1 {
        public void DisplayMessage() {
            Console.WriteLine("This method belongs to Class1 in Namespace1");
        }
    }
}

namespace Namespace2 {
    public class Class2 {
        public void DisplayMessage() {
            Console.WriteLine("This method belongs to Class2 in Namespace2");
        }
    }
}

namespace CSharpTutorials {
    class Tutorial {
        static void Main(string[] args) {

            Namespace1.Class1 c1obj = new Namespace1.Class1();
            Namespace2.Class2 c2obj = new Namespace2.Class2();

            c1obj.DisplayMessage();
            c2obj.DisplayMessage();

            Console.ReadKey();
        }
    }
}

Download the code

In the above code two namespaces Namespac1 and Namespace2 have been declared. The first namespace contains a class named Class1 while the second namespace contains Class2. To access a class within a namespace you need to write the name of the namespace followed by a dot operator and the class name. However, if you add namespace at the top via using keyword you do not need to write fully qualified class name. Have a look at this example.

´╗┐using System;
using Namespace1;
using Namespace2;

namespace Namespace1 {
    public class Class1 {
        public void DisplayMessage() {
            Console.WriteLine("This method belongs to Class1 in Namespace1");
        }
    }
}

namespace Namespace2 {
    public class Class2  {
        public void DisplayMessage() {
            Console.WriteLine("This method belongs to Class2 in Namespace2");
        }
    }
}

namespace CSharpTutorials {
    class Tutorial  {
        static void Main(string[] args) {

            Class1 c1obj = new Class1();
            Class2 c2obj = new Class2();

            c1obj.DisplayMessage();
            c2obj.DisplayMessage();

            Console.ReadKey();
        }
    }
}

Download the code

In the above code Class1 and Class2 classes are being used without namespace names. This is because their namespaces have been added at the top via using keyword.

<<< Extension Methods in C#Static Classes and Members >>>
Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .