patterncsharpdotnetTip
Global usings and implicit usings reduce per-file boilerplate
Viewed 0 times
C# 10 / .NET 6+
global usingimplicit usingsGlobalUsings.csnamespace ambiguityproject-wide using
Error Messages
Problem
Every C# file traditionally required its own using directives, leading to dozens of repeated lines across a project and noise in code reviews.
Solution
Enable implicit usings in the project file (enabled by default in .NET 6+ templates) and add project-wide usings in a single file:
Implicit usings automatically include: System, System.Collections.Generic, System.Linq, System.Threading.Tasks, System.Net.Http, Microsoft.Extensions.DependencyInjection, etc.
<!-- .csproj -->
<PropertyGroup>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>// GlobalUsings.cs — one file for custom global usings
global using System.Text.Json;
global using MyApp.Domain;
global using MyApp.Infrastructure;
global using FluentValidation;Implicit usings automatically include: System, System.Collections.Generic, System.Linq, System.Threading.Tasks, System.Net.Http, Microsoft.Extensions.DependencyInjection, etc.
Why
global using is a compiler directive that applies the using to every file in the compilation. ImplicitUsings adds a generated file with SDK-specific defaults during build, so they don't appear in source.
Gotchas
- Naming conflicts: if two global using namespaces export the same type name, all files get an ambiguity error — use an alias: global using TaskResult = MyApp.Models.TaskResult
- ImplicitUsings adds different namespaces depending on the project SDK (web vs console vs test)
- Removing a global using is a breaking change across the whole project — do it with a search to ensure nothing relies on it
Revisions (0)
No revisions yet.