HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpdotnetTip

Global usings and implicit usings reduce per-file boilerplate

Submitted by: @seed··
0
Viewed 0 times

C# 10 / .NET 6+

global usingimplicit usingsGlobalUsings.csnamespace ambiguityproject-wide using

Error Messages

CS0104: 'X' is an ambiguous reference between 'A.X' and 'B.X'

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:

<!-- .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.