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 can be hidden entirely.
Code
C#
// 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();
}
}C#
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 usingstatements in a single shared obvious file likeGlobalUsings.csalthough this isn't required - You can enable implicit usings 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 statements