With .Net 6 in preview, it's time to look forward to the new version of C# 10 we'll see released later this year. This first post in a series of blogs about C# 10 will be discussing Global Using Statements.
If you are familiar with developing in C#, you will be used to our .cs files starting with several lines that look like this:
using Umbraco.Extensions;
These are scoped to the file we are working in. If we need to reference the same usings in several classes, we need to duplicate that code in all of them that need it.
In C#10, we can use the new feature to have a global scoped usings file that will be applied to all classes. These can be identified by using the global keyword and should be in a single file per project. This file can be of any name, but best practice would be something that clearly shows what it is such as a usings.cs or I have also seen an example of .usings file by Christos Matskas.
Here is an example from an Umbraco v9 project (running on .Net 6 preview):
Now, the Program.cs looks a little odd to experienced C# developers (but lovely and tidy!) as we have no usings, straight to the rest of the code needed for the class. This is because all of the imports that are required for this are all in the usings.cs and therefore used automatically.
If we have other classes that need additional imports, they can be defined as usual in the class. Like the Startup.cs below. Or they can be added to the global usings file as appropriate.
The IDE (I am running Visual Studio 2019 preview) will let you know if you try to add an import you have as a global using in another file. For example, here I have tried to add a reference to System which is already in the usings.cs file. The project will still compile, but there is a warning and it's best practice to tidy this up.
Thoughts?
In the recent versions of C#, it's been clear that readability of code has been a priority and our .cs files are getting smaller, while hopefully maintaining readability. I personally think this is a positive step for the language and look forward to seeing standard conventions as more developers use it.
Similar Posts
- https://carole.dev/blog/top-level-programs-in-c-9/
- https://carole.dev/blog/working-with-umbraco-v9-beta-in-cli/