C# Namespaces

In this chapter you will learn:

  1. What are C# Namespaces
  2. Example C# Namespaces
  3. namepace keyword
  4. How to create hierarchical namespace

Description

A namespace is a domain within which type names must be unique.

Types are typically organized into hierarchical namespaces to avoid naming conflicts and to make type names easier to find.

Example

For example, the RSA type that handles public key encryption is defined within the following namespace:

System.Security.Cryptography

A namespace forms an integral part of a type's name. The following code calls RSA's Create method:


System.Security.Cryptography.RSA rsa = System.Security.Cryptography.RSA.Create(); 

namepace keyword

The namepace keyword defines a namespace for types within that block.

For example:


namespace Outer.Middle.Inner/*www  .  j  a va2s .  co  m*/
{                                                                                            
  class Class1 {} 
  class Class2 {} 
} 

The dots in the namespace indicate a hierarchy of nested namespaces. The code that follows is semantically identical to the preceding example:


namespace Outer /*from  ww  w .j  a v a  2 s.  com*/
{ 
  namespace Middle 
  { 
    namespace Inner 
    { 
      class Class1 {} 
      class Class2 {} 
    } 
  } 
} 

We can refer to a type with its fully qualified name, which includes all namespaces from the outermost to the innermost. For example,


Outer.Middle.Inner.Class1;
Outer.Middle.Inner.Class2;

Example 2

C# uses dot to indicate the namespace hierarchy. The following two code blocks have the same namespaces.


namespace A.B.C{/*from www. j a v a  2  s.  co  m*/

}

namespace A{
   namespace B{
      namespace C{
      
      }
   }
}

Next chapter...

What you will learn in the next chapter:

  1. What is namespace using Directive
  2. Example for C# namespace using Directive
  3. using statement and namespace
  4. Namespaces prevent name conflicts
Home »
  C# Tutorial »
    C# Types »
      C# Namespace
C# Namespaces
C# namespace using Directive
C# Aliasing Types and Namespaces
C# global namespace