Thursday, March 24, 2016

Namespaces in C#

In today's post, I will be discussing namespaces in C#. We will see how they are useful to us and some new features introduced in C# 6.

Namespace in C#

Namespaces are great for organizing classes into separate chunks. The .NET framework itself uses namespaces to organize it's huge number of classes. Even we can use namespaces to organize our classes in any fairly large project.

Namespace in C#

Using Directive

In order to access any class, we can use fully qualified name. For example,

System.Console.WriteLine("Hello World");

Or, we can access any namespace in our program using "using" directive. So if we have

using System;

at the top, then we can skip the word "System" and write our line as follows:

Console.WriteLine("Hello World");

Mostly, people prefer to write this way as it's shorter and less cluttered. In some cases, people like to write fully qualified names in order to avoid any confusion.

Namespace keyword

We can define namespace using "namespace" keyword.

namespace ns1
        public class cl1

namespace ns2
        public class cl2

In our main() method, we can use them like this:

   ns1.cl1 obj1 = new ns1.cl1();

   ns2.cl2 obj2 = new ns2.cl2();

Or use using keyword as explained above.

Namespace Alias

May times, if we have same class name in multiple namespaces and we are using both namespaces in the same file, the compiler might get confused which class are we trying to use. We can avoid such a scenario (called namespace collision) either by using fully qualified name as shown above or by using an alias like this:

using a1 = ns1.cl1;

So now we can use this alias to define our object like this:

a1 obj1 = new a1();

Static Using Directive

Since C# 6 onwards, we can use "using static" for static classes. This helps us to write only the method names directly. For example, if we use

using static System.Console;

I can directly use WriteLine() method like this:

WriteLine("Hello World");

instead of using Console.WriteLine() everywhere. So, this helps us write less cluttered code and quicker development :)


Namespaces are a great way for organizing our code into a more manageable manner. Having a good understanding of how to use it makes the code easy to read and understand.

For future updates to my weekly blog, please subscribe to my blog via the "Subscribe To Weekly Post" feature at the right and follow me on Twitter. Until then Happy Coding :)

1 comment:

  1. Great post explaining namespaces and their utility. As an professional developer and a part-time instructor, i'd reference this post for refreshing on namespaces, and I would definitely recommend it to my students as a way to better understand namespaces.