How I organize my global usings

post-thumb

TL;DR: I use implicit global usings for all global using directives in .NET6 projects. I use a separate GlobalUsings.cs file for all global usings in non-.NET6 projects.

Global usings are a new language feature introduced with C# 10 allowing us developers to reduce clutter by defining a using-statement just once for the whole project so it doesn’t has to be repeated in every file accessing the imported namespace. Which is kind of nice, but immediately raised the question in my head how to organize these global usings without creating an intransparent mess.

A base principle for organizing global usings should be in my opinion to just strictly consolidate them in one file and to not distribute them between multiple source files. This makes it more transparent which global usings are defined. Implicit global usings in .NET6 also follow that approach. And additionally, they are well integrated by making use of the build system - and so can we.

Implicit global usings

Implicit global usings is a new opt-in feature in .NET6 where some common namespaces (like System) can be made available globally in your project without explicitly defining any (global) usings for them. It can be enabled by adding

<ImplicitUsings>enable</ImplicitUsings>

to your .csproj-file and is on by default for new projects.

Under the hood this is powered by the MSBuild system which auto-generates a <YOUR_PROJECT_NAME>.GlobalUsings.g.cs-file in the obj-directory as a pre-compilation step containing the global usings later consumed by the compiler. Which ones these are by default depends on the type of project, for example whether it is a Console or Web Application.

But, we can configure that.

An MSBuild item group for managing the generated global usings allows us to control which namespaces will be implicitly included or excluded. The following item group for example removes the default implicit global using of System and adds an implicit global using for System.Text.Json.

<ItemGroup>
  <Using Remove="System">
  <Using Include="System.Text.Json" />
</ItemGroup>

Conclusion

Consolidate all global usings in a single file e.g. GlobalUsings.cs.

In .NET6 there actually is already such a file where global usings are consolidated in - namely the auto-generated one by the SDK. Use an MSBuild item group for configuring all global usings in the .csproj-file. This has the advantage of

  1. managing both implicit and explicit global usings in one place (by making them all implicit)
  2. not cluttering the project’s source directory with an additional file for global usings

How do you use and organize global usings in your projects?

Der Objektkultur-Newsletter

Mit unserem Newsletter informieren wir Sie stets über die neuesten Blogbeiträge,
Webcasts und weiteren spannende Themen rund um die Digitalisierung.

Newsletter abonnieren