Global usings were introduced in C# 10 to make it easier to include often/frequently used namespaces in a project. Global usings make it possible to consolidate repetitive using namespaces into one single file.
All namespaces declared in a global using file will automatically be available for all files to use throughout all classes, etc... in your project. I personally like this feature as it saves me time and takes out the clutter from my code turning it into a more readable solution.
This is a short post to keep things simple and clear. If you are ready, then let's dig in and learn why and how to use global usings / global using directives.
Why should you use Global usings?
If you use the same namespaces a lot like
System.IO if your app is working with files, etc... it would be obvious to include that namespace in the
If you add it you would be able to use methods from that namespace without having to add the
System.IO namespace in every single class file where you reference them. Here is an example:
global using System.IO
How to use global usings / global using
To keep things a bit clean I tend to add comments in my
GlobalUsings.cs file. why? If you got multiple projects in your solution, you can reference them all in a single file along with 3rd party directives, etc...
Here is an example of a
GlobalUsings.cs file with comments and references to multiple projects.
// Project Namespaces
global using SomeProjectName.Core.Application
global using SomeProjectName.Core.Domain
global using SomeProjectName.Infrastructure
global using SomeProjectName.API
// 3rd party directives
global using Microsoft.Extensions.DependencyInjection
global using Newtonsoft.Json
global using Serilog
global using System.Text.Json
GlobalUsings.cs is not a file that is created automatically in your project, unlike
GlobalUsings.cs is an optional file and you have to add it manually to your project. I always place mine at the root of my project.
Inside your using directives file (`GlobalUsings.cs`) you can add as many statements as you would like to. Please remember to include comments to keep things more clear. This will help you in the future, but also other developers if they have to do any maintenance on the application.
You don't have to place all using statements you use in your project in this file. You should only add those you use frequently.
In this short post, you learned about Global Using Directives / Global Usings in C#. You are now able to declare them and use them in your project.
By using global usings we can write cleaner code starting from C# 10 applications. It's generally a good idea to keep the list of global usings concise as it can grow big pretty fast if your project depends on a lot of other directives.
If you got any questions or suggestions about the contents of this post, please let me know in the comments below, by signing in. Until next time - Happy coding ✌️