Movatterモバイル変換


[0]ホーム

URL:


Skip to main content

This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

Download Microsoft EdgeMore info about Internet Explorer and Microsoft Edge
Table of contentsExit focus mode

Theusing directive

  • 2025-01-27
Feedback

In this article

Theusing directive allows you to use types defined in a namespace without specifying the fully qualified namespace of that type. In its basic form, theusing directive imports all the types from a single namespace, as shown in the following example:

using System.Text;

You can apply two modifiers to ausing directive:

  • Theglobal modifier has the same effect as adding the sameusing directive to every source file in your project.
  • Thestatic modifier imports thestatic members and nested types from a single type rather than importing all the types in a namespace.

You can combine both modifiers to import the static members from a type to all source files in your project.

You can also create an alias for a namespace or a type with ausing alias directive.

using Project = PC.MyCompany.Project;

You can use theglobal modifier on ausing alias directive.

Note

Theusing keyword is also used to createusing statements, which help ensure thatIDisposable objects such as files and fonts are handled correctly. For more information about theusing statement, seeusing statement.

The scope of ausing directive without theglobal modifier is the file in which it appears.

Theglobal using directive must appear before all namespace and type declarations. All global using directives must appear in a source file before any nonglobalusing directives.

Otherusing directives can appear:

  • At the beginning of a source code file, before any namespace or type declarations.
  • In any blocked-scoped namespace, but before any namespaces or types declared in that namespace.

Otherwise, a compiler error is generated.

Create ausing directive to use the types in a namespace without having to specify the namespace. Ausing directive doesn't give you access to any namespaces that are 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. For a list of the system-defined namespaces, see.NET API Browser.

Theglobal modifier

Adding theglobal modifier to ausing directive means that using is applied to all files in the compilation (typically a project):

global using <fully-qualified-namespace>;

Wherefully-qualified-namespace is the fully qualified name of the namespace whose types can be referenced without specifying the namespace.

Aglobal using directive can appear at the beginning of any source code file. Allglobal using directives in a single file must appear before:

  • Allusing directives without theglobal modifier.
  • All namespace and type declarations in the file.

You can addglobal using directives to any source file. Typically, you want to keep them in a single location. The order ofglobal using directives doesn't matter, either in a single file, or between files.

Theglobal modifier can be combined with thestatic modifier. Theglobal modifier can be applied to ausing alias directive. In both cases, the directive's scope is all files in the current compilation. The following example enables using all the methods declared in theSystem.Math in all files in your project:

global using static System.Math;

You can also globally include a namespace by adding a<Using> item to your project file, for example,<Using Include="My.Awesome.Namespace" />. For more information, see<Using> item.

Analyzers issue diagnostics if you duplicateglobal using directives in different locations. These same analyzers also inform you if you add ausing directive for a namespace or type that aglobal using directive already references. You might find it easier to manage yourglobal usings by keeping them together in one file in the project.

Important

The C# templates for .NET 6 usetop level statements. Your application may not match the code in this article, if you've already upgraded to the .NET 6. For more information see the article onNew C# templates generate top level statements

The .NET 6 SDK also adds a set ofimplicitglobal using directives for projects that use the following SDKs:

  • Microsoft.NET.Sdk
  • Microsoft.NET.Sdk.Web
  • Microsoft.NET.Sdk.Worker

These implicitglobal using directives include the most common namespaces for the project type.

For more information, see the article onImplicit using directives

Thestatic modifier

Theusing static directive names a type whose static members and nested types you can access without specifying a type name. Its syntax is:

using static <fully-qualified-type-name>;

The<fully-qualified-type-name> is the name of the type whose static members and nested types can be referenced without specifying a type name. If you don't provide a fully qualified type name (the full namespace name along with the type name), C# generates compiler errorCS0246: "The type or namespace name 'type/namespace' couldn't be found (are you missing a using directive or an assembly reference?)".

Theusing static directive applies to any type that has static members (or nested types), even if it also has instance members. However, instance members can only be invoked through the type instance.

You can access static members of a type without having to qualify the access with the type name:

using static System.Console;using static System.Math;class Program{    static void Main()    {        WriteLine(Sqrt(3*3 + 4*4));    }}

Ordinarily, when you call a static member, you provide the type name along with the member name. Repeatedly entering the same type name to invoke members of the type can result in verbose, obscure code. For example, the following definition of aCircle class references many members of theMath class.

using System;public class Circle{   public Circle(double radius)   {      Radius = radius;   }   public double Radius { get; set; }   public double Diameter   {      get { return 2 * Radius; }   }   public double Circumference   {      get { return 2 * Radius * Math.PI; }   }   public double Area   {      get { return Math.PI * Math.Pow(Radius, 2); }   }}

By eliminating the need to explicitly reference theMath class each time a member is referenced, theusing static directive produces cleaner code:

using System;using static System.Math;public class Circle{   public Circle(double radius)   {      Radius = radius;   }   public double Radius { get; set; }   public double Diameter   {      get { return 2 * Radius; }   }   public double Circumference   {      get { return 2 * Radius * PI; }   }   public double Area   {      get { return PI * Pow(Radius, 2); }   }}

using static imports only accessible static members and nested types declared in the specified type. Inherited members aren't imported. You can import from any named type with ausing static directive, including Visual Basic modules. If F# top-level functions appear in metadata as static members of a named type whose name is a valid C# identifier, then the F# functions can be imported.

using static makes extension methods declared in the specified type available for extension method lookup. However, the names of the extension methods aren't imported into scope for unqualified reference in code.

Methods with the same name imported from different types by differentusing static directives in the same compilation unit or namespace form a method group. Overload resolution within these method groups follows normal C# rules.

The following example uses theusing static directive to make the static members of theConsole,Math, andString classes available without having to specify their type name.

using System;using static System.Console;using static System.Math;using static System.String;class Program{   static void Main()   {      Write("Enter a circle's radius: ");      var input = ReadLine();      if (!IsNullOrEmpty(input) && double.TryParse(input, out var radius)) {         var c = new Circle(radius);         string s = "\nInformation about the circle:\n";         s = s + Format("   Radius: {0:N2}\n", c.Radius);         s = s + Format("   Diameter: {0:N2}\n", c.Diameter);         s = s + Format("   Circumference: {0:N2}\n", c.Circumference);         s = s + Format("   Area: {0:N2}\n", c.Area);         WriteLine(s);      }      else {         WriteLine("Invalid input...");      }   }}public class Circle{   public Circle(double radius)   {      Radius = radius;   }   public double Radius { get; set; }   public double Diameter   {      get { return 2 * Radius; }   }   public double Circumference   {      get { return 2 * Radius * PI; }   }   public double Area   {      get { return PI * Pow(Radius, 2); }   }}// The example displays the following output://       Enter a circle's radius: 12.45////       Information about the circle://          Radius: 12.45//          Diameter: 24.90//          Circumference: 78.23//          Area: 486.95

In the example, theusing static directive could also be applied to theDouble type. Adding that directive would make it possible to call theTryParse(String, Double) method without specifying a type name. However, usingTryParse without a type name creates less readable code, since it becomes necessary to check theusing static directives to determine which numeric type'sTryParse method is called.

using static also applies toenum types. By addingusing static with the enum, the type is no longer required to use the enum members.

using static Color;enum Color{    Red,    Green,    Blue}class Program{    public static void Main()    {        Color color = Green;    }}

Theusing alias

Create ausing alias directive to make it easier to qualify an identifier to a namespace or type. In anyusing directive, the fully qualified namespace or type must be used regardless of theusing directives that come before it. Nousing alias can be used in the declaration of ausing directive. For example, the following example generates a compiler error:

using s = System.Text;using s.RegularExpressions; // Generates a compiler error.

The following example shows how to define and use ausing 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            var mc = new Project.MyClass();        }    }    namespace MyCompany    {        namespace Project        {            public class MyClass { }        }    }}

A using alias directive can't have an open generic type on the right-hand side. For example, you can't create a using alias for aList<T>, but you can create one for aList<int>.

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

using System;// Using alias directive for a class.using AliasToMyClass = NameSpace1.MyClass;// Using alias directive for a generic class.using UsingAlias = NameSpace2.MyClass<int>;namespace NameSpace1{    public class MyClass    {        public override string ToString()        {            return "You are in NameSpace1.MyClass.";        }    }}namespace NameSpace2{    class MyClass<T>    {        public override string ToString()        {            return "You are in NameSpace2.MyClass.";        }    }}namespace NameSpace3{    class MainClass    {        static void Main()        {            var instance1 = new AliasToMyClass();            Console.WriteLine(instance1);            var instance2 = new UsingAlias();            Console.WriteLine(instance2);        }    }}// Output://    You are in NameSpace1.MyClass.//    You are in NameSpace2.MyClass.

Beginning with C# 12, you can create aliases for types that were previously restricted, includingtuple types, pointer types, and other unsafe types. For more information on the updated rules, see thefeature spec.

Qualified alias member

The namespace alias qualifier,:: provides explicit access to the global namespace or other using aliases potentially hidden by other entities.

Theglobal:: ensures that the namespace lookup for the namespace following the:: token is relative to the global namespace. Otherwise, the token must resolve to a using alias, and the token following the:: must resolve to a type in that aliased namespace. The following example shows both forms:

using S = System.Net.Sockets;class A{    public static int x;}class C{    public void F(int A, object S)    {        // Use global::A.x instead of A.x        global::A.x += A;        // Using ::, S must resolve to a namespace alias:        S::Socket s = S as S::Socket;        // In this form, if S were a class, it would be a compile-time error:        S.Socket s1 = S as S.Socket;    }}

C# language specification

For more information, seeUsing directives in theC# Language Specification. The language specification is the definitive source for C# syntax and usage.

For more information on theglobal using modifier, see theglobal usings feature specification.

See also

Collaborate with us on GitHub
The source for this content can be found on GitHub, where you can also create and review issues and pull requests. For more information, seeour contributor guide.

Feedback

Was this page helpful?

YesNo

In this article

Was this page helpful?

YesNo