using directive - C# reference (2024)

  • Article

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

using System.Text;

You can apply two modifiers to a using directive:

  • The global modifier has the same effect as adding the same using directive to every source file in your project. This modifier was introduced in C# 10.
  • The static modifier imports the static 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 in all source files in your project.

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

using Project = PC.MyCompany.Project;

You can use the global modifier on a using alias directive.

Note

The using keyword is also used to create using statements, which help ensure that IDisposable objects such as files and fonts are handled correctly. For more information about the using statement, see using statement.

The scope of a using directive without the global modifier is the file in which it appears.

The using directive can appear:

  • At the beginning of a source code file, before any namespace or type declarations.
  • In any namespace, but before any namespaces or types declared in that namespace, unless the global modifier is used, in which case the directive must appear before all namespace and type declarations.

Otherwise, compiler error CS1529 is generated.

Create a using directive to use the types in a namespace without having to specify the namespace. A using 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.

global modifier

Adding the global modifier to a using directive means that using is applied to all files in the compilation (typically a project). The global using directive was added in C# 10. Its syntax is:

global using <fully-qualified-namespace>;

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

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

  • All using directives without the global modifier.
  • All namespace and type declarations in the file.

You may add global using directives to any source file. Typically, you'll want to keep them in a single location. The order of global using directives doesn't matter, either in a single file, or between files.

The global modifier may be combined with the static modifier. The global modifier may be applied to a using 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 the System.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.

Important

The C# templates for .NET 6 use top 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 on New C# templates generate top level statements

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

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

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

For more information, see the article on Implicit using directives

static modifier

The using 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 error CS0246: "The type or namespace name 'type/namespace' couldn't be found (are you missing a using directive or an assembly reference?)".

The using 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 a Circle class references many members of the Math 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 the Math class each time a member is referenced, the using 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 a using 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 different using 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 the using static directive to make the static members of the Console, Math, and String 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, the using static directive could also have been applied to the Double type. Adding that directive would make it possible to call the TryParse(String, Double) method without specifying a type name. However, using TryParse without a type name creates less readable code, since it becomes necessary to check the using static directives to determine which numeric type's TryParse method is called.

using static also applies to enum types. By adding using 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; }}

using alias

Create a using alias directive to make it easier to qualify an identifier to a namespace or type. In any using directive, the fully qualified namespace or type must be used regardless of the using directives that come before it. No using alias can be used in the declaration of a using 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 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 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 a List<T>, but you can create one for a List<int>.

The following example shows how to define a using directive and a using 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, including tuple types, pointer types, and other unsafe types. For more information on the updated rules, see the feature spec.

C# language specification

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

For more information on the global using modifier, see the global usings feature specification - C# 10.

See also

  • C# keywords
  • Namespaces
  • Style rule IDE0005 - Remove unnecessary 'using' directives
  • Style rule IDE0065 - 'using' directive placement
  • using statement
using directive - C# reference (2024)

FAQs

What is the purpose of using directive in C#? ›

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

What is redundant using directive? ›

Code inspection: Redundant using directive

If your project is targeting C# 10.0 or later, you may see a using directive highlighted as redundant in a file where symbols from the referenced namespace are actually used. This means that the namespace is referenced elsewhere in the project via a global using directive.

How do you declare using inside namespace? ›

For the declaration to work, the member must be declared inside the given namespace. For example: namespace A { int i; int k; void f(){}; void g(){}; } using A::k; In this example, the using declaration is followed by A , the name of namespace A , which is then followed by the scope operator ( :: ), and k .

What is global using in C#? ›

Global usings are a new feature in C# 10 that give you the ability to declare a using directive over every source file in your project instead of needing to duplicate the declaration inside of each file in your projects!

What is the advantage of directive? ›

What are the benefits of using directive leadership? Despite some clear negatives that have historically been associated with directive leadership, there are some benefits. Using a directive leadership approach on the organizational level can clarify actions, give structure to tasks, and achieve goals more efficiently.

Why and when do we use directive in C? ›

In C, macro definition directives uses the #define preprocessor directive to define the macros and symbolic constants. We use #define directive to define macro. Macro are basically the symbolic names that represents lines of code or some values.

Why is directive unnecessary? ›

"Using directive is unnecessary" means that nothing in the current C# code file is referencing a non-namespace qualified type in the namespace of the using directive. To fix this warning you either need to remove the using directive or add some code that uses a type in the namespace the using statement refers to.

Is redundancy good in coding? ›

Programming languages extensively use this to reduce coding errors. If there was no redundancy at all in a language, then any random sequence of characters would be a valid program. Every error message generated by the compiler is an example of redundancy in the language that finds user errors.

How do you avoid code redundancy? ›

Extracting Methods: Identify common code segments and extract them into reusable methods. By consolidating duplicate logic into a single method, you can reduce redundancy and promote reusability.

What is using declaration in C#? ›

With the C# 8.0 update, Microsoft has introduced the using declaration feature. This feature allows us to declare a disposable object with the keyword using so the object will be disposed of when it goes out of the scope.

What is the correct way of declaring namespace? ›

A file containing a namespace must declare the namespace at the top of the file before any other code - with one exception: the declare keyword.

How do you use namespace correctly? ›

Typically, you declare a namespace in a header file. If your function implementations are in a separate file, then qualify the function names, as in this example. A namespace can be declared in multiple blocks in a single file, and in multiple files.

What is the difference between using directive and using statement in C#? ›

In C#, the using keyword has two purposes: The first is the using directive, which is used to import namespaces at the top of a code file. The second is the using statement. C# 8 using statements ensure that classes that implement the IDisposable interface call their dispose method.

What is the difference between implicit using and global using? ›

Implicit usings let you include the . NET namespaces appropriate to the kind of project you're building with a single line in your project file. global using directives let you include additional namespaces to make them available throughout your project.

What does using static do in C#? ›

In C#, static is used to define members that belong to a type rather than an instance of the type. This means that a static member is shared among all instances of a class, rather than being unique to each instance.

What are the purposes of using directives? ›

The primary function of the using directive is to make types within a namespace available without qualification to the user code. It considers the set of namespaces and types which are defined in referenced assemblies and the project being compiled.

What is the primary purpose of a directive? ›

The purpose of the directive is to give an order, request, prohibition, or invitation, depending on the context and situation. The purpose of the directive is to get the recipient to carry out or refrain from action.

Why do we use include directive in C? ›

#include is another preprocessor directive in C. It is used to include the contents of another file in the current file. While writing a C program, you are by default supposed to include some important header files as per your use – especially stdio.

What is the purpose of directives in a .NET page? ›

Directives specify settings that are used by the page and user-control compilers when the compilers process ASP.NET Web Forms pages (. aspx files) and user control (.

References

Top Articles
Latest Posts
Article information

Author: Nicola Considine CPA

Last Updated:

Views: 5428

Rating: 4.9 / 5 (69 voted)

Reviews: 92% of readers found this page helpful

Author information

Name: Nicola Considine CPA

Birthday: 1993-02-26

Address: 3809 Clinton Inlet, East Aleisha, UT 46318-2392

Phone: +2681424145499

Job: Government Technician

Hobby: Calligraphy, Lego building, Worldbuilding, Shooting, Bird watching, Shopping, Cooking

Introduction: My name is Nicola Considine CPA, I am a determined, witty, powerful, brainy, open, smiling, proud person who loves writing and wants to share my knowledge and understanding with you.