global modifier
- The
global using
directive was added in C# 10 - Adding the
global
modifier to ausing
directive means that using is applied to all files in the compilation (typically a project).
global using System
Rules
global using
directives must appear before
- All using directives without the global modifier.
- All namespace and type declarations in the file.
- The order of global using directives doesn't matter, either in a single file, or between files.
File
You can put global usings
in any .cs
file, including Program.cs
or a specifically named file like globalusings.cs
.
With Static modifier
The global modifier may be combined with the static modifier.
Declare
global using static System.Math;
Use
Console.WriteLine(Round(2.5678));
instead of
Console.WriteLine(Math.Round(2.5678));
Adding static, imports a type and makes the type’s members and nested types available throughout your project.
With Alias
The global modifier may be applied to a using alias directive.
Declare
global using Env = System.Environment;
Use
Console.WriteLine(Env.OSVersion);
instead of
Console.WriteLine(System.Environment.OSVersion);
In Project File
You can also globally include a namespace by adding a <Using>
item to your project file
<Using Include="System.IO" />
Implicit global using
Implicit global using
directives are added in new C# projects to a generated file in the project's obj directory.
Implicit global using directives are added for projects that use one of the following SDKs:
- Microsoft.NET.Sdk
- Microsoft.NET.Sdk.Web
- Microsoft.NET.Sdk.Worker
- Microsoft.NET.Sdk.WindowsDesktop
Default Namespaces for Microsoft.Net.Sdk
- System
- System.Collections.Generic
- System.IO
- System.Linq
- System.Net.Http
- System.Threading
- System.Threading.Tasks
Enable ImplicitUsing
To enable implicit usings set the ImplicitUsings
property in your .csproj file:
<PropertyGroup>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
References
- https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-10
- https://devblogs.microsoft.com/dotnet/welcome-to-csharp-10/
- https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/using-directive#global-modifier
- https://docs.microsoft.com/en-us/dotnet/core/project-sdk/overview#implicit-using-directives