Breaking

Wednesday, September 29, 2021

C# 10–Global using

I continue my journey in discovering possibilities of the ‘using’ keyword and arrive at an upcoming feature in C# 10: global using directives.

C# 10.0 allows you to define using directives globally, so that you don’t have to write them in every file. Let’s take a look at a simple example.

I created a GlobalUsings.cs class in my project and added the following 2 lines:

By doing this the 2 namespaces above are available in every C# file in my project.

Remark: In this example I’ve put my global usings in a seperate file. This isn’t necessary, you can put the global usings in any code file, although I would recommend isolating it to make them easier to discover and maintain.

Now I can simplify my Program.cs file:

You can combine this feature with the using static as well:

This allows me to even further simplify my Program.cs file:

More information: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/using-directive#global-modifier

No comments:

Post a Comment