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