Category Archives: C#, VB

Understanding Namespaces

Understanding Namespaces using C#

Namespaces are heavily used in object oriented programming languages. All .NET Framework classes are organized in namespaces to help developers organize their code more clearly and to avoid chaos. Furthermore, custom namespaces are extensively used by programmers, both to organize their work and to avoid naming collisions.

Implementing namespaces in your own code is a good habit because it is likely to save you from problems later when you want to reuse some of your code.

When referencing a class, you should specify either its fully qualified name, which means namespace followed by the class name.


System.Console.WriteLine("Hello World!");
int i = Convert.ToInt32("123");

In the above examples, System is a .NET namespace, and Console and Convert are classes defined within System.

Another way to program this is the USING directive.


Using System;
Using System.Text;


Each USING directive lists the namespaces that the application will be using frequently, and saves you from specifying a fully qualified name every time that a method is used.
So instead of :


System.Console.WriteLine("Hello World");

You can replace it with:


USING System;
Console.WriteLine("Hello World");

SCOPE
Namespaces are also used to declare a scope. By creating scopes in your project, you will better organize your code and you can create globally unique types. Namespaces can also be nested inside another namespace.


namespace myUniquenamespace
{
     class mySampleClass
      { 
          public void SampleMethod()
           {
            System.Console.WriteLine ("Hello World");
           }
       }

// Create a nested namespace, and define another class.

namespace myNestedNamespace
   {
    class mySampleClass2
        {
          public void SampleMethod()
             {
              System.Console.WriteLine ("hello world");
             }
        }
    }

}

FULLY QUALIFIED NAMES

namespace n1 //n1
    {
       class class1
         {
           class class2 // n1.class1.class2
             {
             }
         }
 namespace n2 // n1.n2
         {
         class class2 // n1.n2.class2
       {
       }
    }
}


The fully qualified namespace n1 is a member of the global namespace.

The namespace n2 is a member of n1. The fully qualified name is n1.n2

The class class1 is a member of n1 and the fully qualified name is n1.class1.

The class name class2 is used twice in this code. However, the fully qualified names are unique. The first instance of class1 is declared inside class1 therefore, its fully qualified name is: n1.class1.class2

The second instance of class2 is declared inside a namespace n2 therefore, its fully qualified name is n1.n2.class2