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">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net6.0</TargetFramework>
    <LangVersion>preview</LangVersion>
  </PropertyGroup>

</Project>

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

Course course = await GetSomeCourse();

foreach (
Student student in course.Students)
{
    
Console.WriteLine(student.Name);
}

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

    return await 
Task.FromResult(course);
}

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).
Usings.cs
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.

Regards,
Jaliya

No comments:

Post a Comment