Export (0) Print
Expand All

using Directive

The using directive has two uses:

  • Create an alias for a namespace (a using alias).
  • Permit the use of types in a namespace, such that, you do not have to qualify the use of a type in that namespace (a using directive).
using [alias = ]class_or_namespace;

where:

alias (optional)
A user-defined symbol that you want to represent a namespace. You will then be able to use alias to represent the namespace name.
class_or_namespace
The namespace name that you want to either use or alias, or the class name that you want to alias.

Remarks

Create a using alias to make it easier to qualify an identifier to a namespace or class.

Create a using directive to use the types in a namespace without having to specify the namespace. A using directive does not give you access to any namespaces that may be nested in the namespace you specify.

Namespaces come in two categories: user-defined and system-defined. User-defined namespaces are namespaces defined in your code. See the documentation for the .NET Framework for a list of the system-defined namespaces.

For examples on referencing methods in other assemblies, see Creating and Using C# DLLs.

Example

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

// cs_using_directive.cs
using MyAlias = MyCompany.Proj.Nested;  // define an alias to represent a namespace

namespace MyCompany.Proj 
{
   public class MyClass 
   {
      public static void DoNothing() 
      {
      }
   }

   namespace Nested   // a nested namespace
   {
      public class ClassInNestedNameSpace 
      {
         public static void SayHello() 
         {
            System.Console.WriteLine("Hello");
         }
      }
   }

}

public class UnNestedClass 
{
   public static void Main() 
   {
      MyAlias.ClassInNestedNameSpace.SayHello();   // using alias
   }
}

Output

Hello

Example

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

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

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

namespace NameSpace2 
{
   class MyClass 
   {
   }
}

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

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

Output

You are in NameSpace1.MyClass

See Also

C# Keywords | namespace | using Statement

Show:
© 2014 Microsoft