Introducing C# 10: Global usings, example with ASP.NET Core 6
Introduction
.NET 6 preview 6 has been released a few days ago, and the great news is it brings with new C# 10 features. In this post I will introduce you the usage of Global usings within an ASP.NET Core 6 app with Visual Studio 2022 preview 2. Global usings intend to simplify and lighten C# code, by declaring only once a using keyword on a specific namespace on a same project, then you won’t need to declare in another file which needs the same namespace. Interesting isn’t it ?
Example with ASP.NET Core 6
Because all this stuff is in preview, to make work the following example, you’ll need to add the LangVersion tag in your csproj file, like this:
First I want to share with you my favourite way to use Global usings. I love to deal with single file which contains all usings. After creating your ASP.NET Core 6 app, create a file, for example: GlobalUsings.cs, which is meaningful for me in your project:
Then remove all your usings from your C# files, example with the Startup.cs file:
Add them into the GlobalUsings.cs file with adding the global keyword for each:
You can compile the project, and believe me it works like a charm! 🙂
Remember ! If you are using several projects you’ll have to declare your global usings on each project.