C# 10 - Global Using

c sharp logo

I recently had the chance to start a new project where we are using .NET6 and C#10. So I was able to begin to put into practice some of the new possibilities available to us. In this article, I wanted to expose the use of global using of C# 10, which in my opinion will greatly help for the readability of our code.

Repetitions of usings

Take for example the test classes that I have at the level of an architecture testing project, for which I used ArchUnit (besides we made a Bracket Show episode on this topic). In all of my testing classes I always have this at the top of the file:

Image montrant les using utilisés dans la classe

I could make myself a template for this kind of test class, but it could get exponential depending on the different use cases outside of just this example. Besides, it doesn't remove those few lines from the top of my file.

The global using

Now the global using come to level with this problem. The idea is simple, you just have to add the word global in front of a using, and it will become imported for all classes in a project. This behavior is similar to what we put in the file _Imports.razor of a project made with Blazor. Ideally we place these usings inside a separate, easily identifiable file, and you don't have to worry about it anymore.

With this we will even have a warning from Visual Studio if we try to add one of these usings in a class, in the same way as if it were duplicated in the class.

Do not abuse

Although very useful, in my opinion you have to be careful not to overdo it. This should be used for what is identified as being common to the whole project. Some imports can be specific to a class, so we should not see them imported globally for the project.

Conclusion

This is a first article on what C# 10 will offer us, others will follow in the coming weeks. What do you think of this feature? Is there anything else from C# 10 that you would like to see covered? Let me know in the comments.

Bruno

Author: Bruno

By day, I am a developer, team leader and co-host of the Bracket Show. By evening, I am a husband and the father of two wonderful children. The time I have left after all of this I spend trying to get moving, playing and writing video game reviews, as well as preparing material for the Bracket Show recordings and for this blog. Through it all, I am also passionate about music and microbreweries.