Introducing Namespaces in C#

In C#, a namespace is used to organize a program. A namespace declaration starts with the keyword namespace and it is followed by the name and body of the namespace. An optional ; (semicolon) can be used to declare a namespace. Listing given below presents an example of the use of the namespace.

Example of the Namespace

Code Snippet
  1. namespace Ch01
  2. {
  3.     class A { }
  4.     class B { }
  5. }

The declaration of the namespace starts with a qualified identifier, which can be a single identifier or multiple identifiers separated with dot (.) tokens. As a result, the following two namespace declarations, as declared in Listing given belows, will be treated the same by the C# compiler.


Namespace Declaration with Multiple Identifier Separator (.)


Code Snippet
  1. namespace Ch01Level3.Ch01Level2.Ch01Level1
  2. {
  3.     class ClassA { }
  4. }


Namespace Declaration with Multiple Identifier Separator (.)



Code Snippet
  1. namespace Ch01Level3
  2. {
  3.     namespace Ch01Level2
  4.     {
  5.         namespace Ch01Level1
  6.         {
  7.             class ClassA { }
  8.         }
  9.     }
  10. }


Namespace with Multiple Identifier


Code Snippet
  1. namespace Ch01Level3.Ch01Level2.Ch01Level1
  2. {
  3.     internal class ClassA
  4.     {
  5.         /* Methods */
  6.         public ClassA();
  7.     }
  8. }


When two namespaces are declared with the same fully qualified name, the C# compiler combines
those declarations of the namespace inside one qualified name, as shown in Listing 1-35.


Multiple Namespace with Same Fully Qualified Name



Code Snippet
  1. namespace Ch01
  2. {
  3.     class ClassA { }
  4. }
  5. namespace Ch01
  6. {
  7.     class ClassB { }
  8. }


Listing below is compiled as shown in Listing 1-36 to combine same namespace declarations.


Code Snippet
  1. Combined Namespace
  2. namespace Ch01
  3. {
  4.     internal class ClassA{}
  5.     internal class ClassB{}
  6.     public class Person{}
  7.     internal class Program{}
  8. }


Usage of the Using Directive


Code Snippet
  1. namespace Ch01.Using
  2. {
  3.     using Ch01;                  /* using statement imports the namespace
  4.                                   * defined in the Listing 1-36 */
  5.     using One = Ch01;              /* using alias directives One refers to
  6.                                   * the Ch01 */
  7.     class ClassC
  8.     {
  9.         private ClassB classB;
  10.         private One.ClassA classA;
  11.     }
  12. }


Post a Comment