Using directives often contain a repeated subset across all the files in a project.
Global using directives allow you to exclude this common boilerplate across your project.
In conjunction with implicit usings (see notes below) using directives can be hidden entirely.
Code
csharp
// In GlobalUsings.cs file
global using System;
global using System.Collections.Generic;
global using System.Linq;
// In EmployeeRepository.cs file
public class EmployeeRepository : Repository {
public List<Employee> GetByDepartment(int departmentId) {
return db.Employees.Where(e => e.DepartmentId == departmentId).ToList();
}
}csharp
using System;
using System.Collections.Generic;
using System.Linq;
public class EmployeeRepository : Repository {
public List<Employee> GetByDepartment(int departmentId) {
return db.Employees.Where(e => e.DepartmentId == departmentId).ToList();
}
}Notes
- Consider putting
global usingdirectives in a single shared obvious file likeGlobalUsings.csalthough this isn't required global usingdirectives must come before any non-global using directives in a file, and also work withstaticand aliases- You can enable implicit usings (.NET 6 SDK onwards) by adding
<ImplicitUsings>enable</ImplicitUsings>to a<PropertyGroup>in your.csprojfile or selectingEnable implicit global usings to be declared by the project SDKin the Visual Studio project settings UI - This is great for unit test projects where you can add
global using Xunit;to your GlobalUsings.cs file and then useFactandTheorywithout any additional using directives