The new C# 10 is packed with quality of life features. One that I'm definitively using is Global Usings.
In simple terms, Global Usings is a way to declare usings at the project level, so you don't need to declare them in every single file.
That's a fair question, especially in the days where IDE's do most of the work for us.
Even then, declaring them at the project level will result in tidier source files. Let's be honest, how many times do you import
System.Linq or your own Extensions namespace?
Global Usings are simple to use. Simply add the
global modifier to the
using you want.
global modifier is the same as adding the same
using directive to every source file in your project.
That leads to the question: Where should I declare my global usings?
I was facing that same question. 🤔
One thing was obvious to me. I should have a central place for it. Even Microsoft Docs say so:
You may add global using directives to any source file. Typically, you'll want to keep them in a single location. The order of global using directives doesn't matter, either in a single file, or between files.
But, where? In a Web or Console project, you may use "Program.cs" for it, but rapidly it may become cluttered. And if it is a Class Library?! There are no "Program.cs".
If you take a look at the comments, you will see many good suggestions around adding a file to the root of the project. Name suggestions vary as you can see:
That seems a good approach, but there was a comment by Martin Costello that made my mind.
Before going into Martin suggestion, it's important to say that you can not only declare
global usings in a
.cs file but also at the project file.
That can be done by adding a
<Using> item to your project file.
<ItemGroup> <Using Include="MyAwesomeApp.Extensions" /> </ItemGroup>
In principle, I would prefer to declare my usings in C#. I don't love to edit my
csproj files, but Martin remembered me that I can do it in a
Directory.Build.props file (if you want to know more about this file, take a look at this post that I've written to see the potential).
The beauty of it is that if you place
Directory.Build.props in the root folder that contains your source code, when MSBuild runs will add to every project the properties defined in the
Directory.Build.props. So, if you want to do it Solution wise or even only for your Test folder, you can do it.
I will be using
Directory.Build.props for sure. At least until we see a new standard way to declare global usings emerging in the community.
I hope that this was useful! To get more tips like this, follow me on Twitter (@gsferreira) and let's keep in touch!