C# namespace using Directive
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 www .j a v a2 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. ja v a 2s. co m*/
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;//w w w. ja v a2s . c o m
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; /* w w w. ja va2 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.