C# namespace using Directive

In this chapter you will learn:

  1. What is namespace using Directive
  2. Example for C# namespace using Directive
  3. using statement and namespace
  4. Namespaces prevent name conflicts

Description

The using directive imports a namespace.

Example

This is a convenient way to refer to types without their fully qualified names.

For example suppose we have the following class definition with namespace;


//from   w w w.  j av a 2 s .  c o  m
namespace Outer 
{ 
  namespace Middle 
  { 
    namespace Inner 
    { 
      class Class1 {} 
      class Class2 {} 
    } 
  } 
} 

Here is the way to use using directive to reference types inside


using Outer.Middle.Inner; //w  w  w  .j ava 2  s .c  om

class Test 
{ 
  static void Main() 
  { 
    Class1 c; 
  } 
} 

Example 2

C# uses using statement to import namespace. Once a namespace is imported we can use its types with simple name(class name).


using System;//from  w  ww . j  av  a  2 s  . c om
using A.B.C;

namespace A
{
    namespace B
    {
        namespace C
        {

            class MyClass
            {

            }
        }
    }
}

class Program
{
    
    static void Main(string[] args)
    {
        MyClass cls = new MyClass();
    }
}

The code above generates the following result.

Example 3


using System;  /* ww w. j a  v a  2  s  . c o m*/
  
namespace Counter {  
  class MyClass {  
    public MyClass(){
      Console.WriteLine("Counter1 namespace."); 
    }
  }  
}  
 
namespace Counter2 {  
  class MyClass { 
    public MyClass() { 
      Console.WriteLine("Counter2 namespace."); 
    } 
  } 
} 
 
class MainClass {  
  public static void Main() {  
    // This is CountDown in the Counter namespace. 
    Counter.MyClass m1 = new Counter.MyClass();  
 
    // This is CountDown in the default namespace. 
    Counter2.MyClass m2 = new Counter2.MyClass(); 
 
  }  
}

The code above generates the following result.

Next chapter...

What you will learn in the next chapter:

  1. What are C# Aliasing Types and Namespaces
  2. Rename the namespaces
  3. How to use the :: qualifier
Home »
  C# Tutorial »
    C# Types »
      C# Namespace
C# Namespaces
C# namespace using Directive
C# Aliasing Types and Namespaces
C# global namespace