Today, in this article, we shall see what namespace actually does and how to organize the classes using namespaces. We use namespaces to organize classes into a logically related hierarchy. Namespaces function as both an internal system for organizing our application and an external way to avoid name collision between source code and application. Because more than one company may create a class with the same name, such as Employee, when we create code, that may be seen or used by third parties. It’s highly recommended that we shall organize our classes by using a hierarchy of namespaces. By practising this, we can avoid interoperability issues on application.

To create a namespace, we simply type a keyword namespace followed by the name. It is recommended to use Pascal case for namespaces.

It is also recommended that you create at least two-tiered namespaces, which is one that contains two levels of classification, separated by a period.

Let us see sample example of a two-tiered namespace.

namespace Infosys.Sales {  
    //define your classes within the namespace  
    public class customer() {}  
}   

Above two-tiered namespace declaration is identical to writing each namespace in nested format, as shown in the following code. 

 

namespace CompanyName {  
    namespace Sales {  
        public class Customer() {}  
    }  
}   

In both cases, we refer to class by using the following code.

CompanyName.Sales.Customer();   

Note

We should avoid creating a class with the same name as namespace.

Commonly used namespaces in .NET Framework
Microsoft .NET Framework is made of many namespaces, the most important one being System. The System namespace contains classes that most of the applications use to interact with operating system.

For example, the system namespace contains the console class which provides several methods, including WriteLine, which is a command that enables us to write code to an on-screen console.

We can access WriteLine method of console as follows.

System.Console.WriteLine("Prem Kumar Rathrola");   

A few of other namespaces that are provided by .NET Framework through the system namespace are listed below. 

  • System.Windows.Forms
    Provides the classes that are useful for building applications based on windows. 
  • System.IO
    Provides classes for reading and writing data to files

  • System.Data
    Provides classes that are useful for data access

  • System.Web
    Provides classes that are useful for building web forms applications