Thursday, May 27, 2021

C# 10.0: Introducing Global Usings

C# 10.0 is expected to ship with .NET 6 in November, 2021 during .NET Conf 2021 (November 9-11), but some of the features are already available with C# Preview LangVersion. One of such features is Global Usings. In this post, let's have a look at what that is.

I have created a Console Application and have set up the LangVersion to preview.

<Project Sdk="Microsoft.NET.Sdk">



Now I have the following code in Program.cs file.

Course course = await GetSomeCourse();

foreach (
Student student in course.Students)

static async 
Task<Course> GetSomeCourse()
Course course = new("C# 10"new List<Student> { new("John"), new("Jane") });

    return await 

public record Student(string Name);

public record Course(string Name
List<Student> Students);

So here you can see I have used some C# 9 features (Top Level statements, Records,  Target-Typed new expressions etc). But here, I don't have any usings. Of course, I need to be having using SystemSystem.Collections.Generic and System.Threading.Tasks here, but where are those?

In my project, I have added another file called Usings.cs (you can name it with any name you want to).
And there in the Usings.cs, I have the following.

global using System;
global using System.Collections.Generic;
global using System.Threading.Tasks;

Note the global keyword. So this means, these usings are available throughout my project. 99% of the time, there will be some usings which needs to be there in every .cs file you have, so basically, you can move all those into a different file and use it with global keyword.

Now let's say, I am adding a new class to the project.
Using appeared previously in this namespace
Compiler immediately identifies we have global usings and we don't have to repeat them here.

Isn't it nice?

Happy Coding.


No comments:

Post a Comment