Global using Directive in C# 10

Global using Directive in C# 10

The global using directive is a new feature that was recently added to C# language in C# version 10.0. This feature allows developers to declare a namespace globally in any one of the files in a project and the global declared namespace is imported and available to all files in the application. The purpose of this feature is to keep the code clean and do not have same duplicate lines of using namespace in every file. For example, if you are using System.SomeNamespace namespace in multiple .cs files, all you need to do is declare globally once and you are done. Even better, if you declare it in project settings file, you don’t even need to add any code and the namespace will be available to all files in the application.

The following code declares a global using namespace. 

global using System.SomeNamespace;

Alternatively, you can globally include a namespace by adding a <Using> item to your project file, for example, <Using Include="System.SomeNamespace" />. 

Implicit using directive

C# 10 and .NET 6.0 introduced implicit using directives, which the C# compiler automatically adds a set of using directives based on the project type. For console applications, the following directives are implicitly included:

using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;

Disable implicit using directives

Adding unused namespace to an application is an unnecessary overhead. You can remove unused namespace that were implicitly imported in the application. 
Add <ImplicitUsings>disable</ImplicitUsings> in the project file to disable app implicit used namespaces. 

Remove an implicit imported namespace

You can remove a specific implicit using directive by added a <Using> item with a Remove attribute to your project file to remove a specific implicit using directive. This is applicable when implicit using is enabled. 


The following entry in the project file removes System. Collections namespace import in the application.

  <Using Remove="System.Collections" />


Recommended Free Ebook
Similar Articles
Founded in 2003, Mindcracker is the authority in custom software development and innovation. We put best practices into action. We deliver solutions based on consumer and industry analysis.