CodeKicks.com
Focus on Microsoft Technologies - Tutorials, Articles, Code Samples.

Thursday, August 24, 2006

Advantages of C# Using Directive

The using directive has two uses:

1). To permit the use of types in a namespace so you do not have to qualify the use of a type in that namespace:

       using System.Text;

2). To create an alias for a namespace or a type.

       using Project = PC.MyCompany.Project;

The using keyword is also be used to create using statements, which define when an object will be disposed. See using Statement for more information.


Example 1:

The following example shows how to define and use a using alias for a namespace:

namespace PC
{
    // Define an alias for the nested namespace.
    using Project = PC.MyCompany.Project;
    class A
    {
        void M()
        {
            // Use the alias
            Project.MyClass mc = new Project.MyClass();
        }
    }
    namespace MyCompany
    {
        namespace Project
        {
            public class MyClass{}
        }
    }
}

Example 2:

The following example shows how to define a using directive and a using alias for a class:

// cs_using_directive2.cs
// Using directive.
using System;  
// Using alias for a class.
using AliasToMyClass = NameSpace1.MyClass;  

namespace NameSpace1
{
    public class MyClass
    {
        public override string ToString()
        {
            return "You are in NameSpace1.MyClass";
        }
    }
}

namespace NameSpace2
{
    class MyClass
    {
    }
}

namespace NameSpace3
{
    // Using directive:
    using NameSpace1;
    // Using directive:
    using NameSpace2;  

    class MainClass
    {
        static void Main()
        {
            AliasToMyClass somevar = new AliasToMyClass();
            Console.WriteLine(somevar);
        }
    }
}

Output

You are in NameSpace1.MyClass

Post a Comment