Basics of .NET Namespace

Namespace are logical grouping of classes and other types such as unions, structures, interfaces and enumerators.

In Microsoft .Net, every program is created with a default namespace. This default namespace is called as global namespace. But the program itself can declare any number of namespaces, each of them with a unique name. The advantage is that every namespace can contain any number of classes, functions, variables and also namespaces etc., whose names are unique only inside the namespace. The members with the same name can be created in some other namespace without any compiler complaints from Microsoft .Net.

If a new project is created in Visual Studio .NET it automatically adds some global namespaces. These namespaces can be different in different projects. But each of them should be placed under the base namespace System.

namespace Books
{
class Authors
{
public void Display()
{
Console.WriteLine("Auther name is Dynamic-Coding");
}
}
This is simple namespace example. We can also build hierarchy of namespace. Here is an example for this.

namespace Books
{
namespace Inventory
{
using System;
class AddInventory
{
public void MyMethod()
{
Console.WriteLine("Adding Inventory via MyMethod!");
}
}
}
}

Let's look how we can use the namespaces in our code

using Books;
class HelloWorld
{
public static void Main()
{
Inventory.AddInventory AddInv = new AddInventory();
AddInv.MyMethod();
}
}

OR

using Books.Inventory;
class HelloWorld
{
public static void Main()
{
AddInventory AddInv = new AddInventory();
AddInv.MyMethod();
}
}

Note:
The namespaces wide opens the doors for 3rd party and project specific custom components and class libraries.

No comments: