I don’t often get hate comments/emails on this blog, but when I do, it’s about using statements not being available in my code snippets. For me, they just clutter everything up and rarely add much value or description to the code. What does several imports from system really add? Especially when everyone these days is using a fully featured IDE that has a one click “Add Using” option when you hover over anything.
Well with .NET 6 / C#10, I now have an excuse with the introduction of global using statements. Now you can place all of your common using statements (So mostly your System imports) into a single file that will automatically be available for use within that entire project. It’s a simple and nifty change!
Getting Setup With .NET 6 Preview
At the time of writing, .NET 6 is in preview, and is not currently available in general release. That doesn’t mean it’s hard to set up, it just means that generally you’re not going to have it already installed on your machine if you haven’t already been playing with some of the latest fandangle features.
To get set up using .NET 6, you can go and read out guide here : https://dotnetcoretutorials.com/2021/03/13/getting-setup-with-net-6-preview/
Remember, this feature is *only* available in .NET 6. Not .NET 5, not .NET Core 3.1, or any other version you can think of. 6.
Additionally, you may need to edit your .csproj file to allow for the preview LangVersion like so :
With all of that done, you should be ready to go!
Adding Global Usings
The syntax for adding global usings is actually fairly straight forward, simply add the keyword global before any using statement, anywhere, to make it global.
global using System;
Interestingly, there isn’t a well defined place to put these yet. You can put these in any file within your project and they are immediately global everywhere (As opposed to say the standard AssembleInfo.cs we used to have).
That being said, I’ve seen many people using a file in the root of your project called GlobalUsings.cs, with something akin to the following in there :
global using System;
global using System.Collections.Generic;
global using System.IO;
global using System.Linq;
//Maybe even a global using of another projects folder folder for instance.
// global using MyModelsProject.Models;
Again, there is no limit to how many usings you can place in here, nor where this file lives, but it’s generally a good idea to keep this list pretty concise only to what you need. That being said, the only downside to overloading these global usings is that your intellisense will be astronomical in every file, whether that’s actually a bad thing I don’t know.
And that’s it!
I’ll note that one of the reasons I love C# and .NET right now is that every single change has a pretty lively discussion on Github. Global Usings is no different and the discussion is out in the public here : https://github.com/dotnet/csharplang/issues/3428. But what’s your thoughts? Drop a comment below!