Skip to content

global using directives C# 10.0readabilitydiscoverability

Specify common using directives to be used across all source files.

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 using statements in a single shared obvious file like GlobalUsings.cs although this isn't required
  • You can enable implicit usings by adding <ImplicitUsings>enable</ImplicitUsings> to a <PropertyGroup> in your .csproj file or selecting Enable implicit global usings to be declared by the project SDK in 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 use Fact and Theory without any additional using statements

More information