C# Namespaces

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// w  ww . j a  v  a  2s .c o 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 ava  2s.co  m
{ 
  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{//  www.  j a  v  a  2s  .c  om

}

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




















Home »
  C# Tutorial »
    Custom Types »




C# Class
C# Struct
C# Interface
C# Inheritance
C# Namespace
C# Object
C# Delegate
C# Lambda
C# Event
C# Enum
C# Attribute
C# Generics
C# Preprocessor