I continue my journey in discovering possibilities of the ‘using’ keyword and arrive at an upcoming feature in C# 10: global using directives.
C# 10.0 allows you to define using directives globally, so that you don’t have to write them in every file. Let’s take a look at a simple example.
I created a GlobalUsings.cs class in my project and added the following 2 lines:
global using System; | |
global using PC.Company.Project; |
By doing this the 2 namespaces above are available in every C# file in my project.
Remark: In this example I’ve put my global usings in a seperate file. This isn’t necessary, you can put the global usings in any code file, although I would recommend isolating it to make them easier to discover and maintain.
Now I can simplify my Program.cs file:
namespace Example | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
var product=new Product(); | |
Console.ReadKey(); | |
} | |
} | |
} |
You can combine this feature with the using static as well:
global using System; | |
global using static System.Console; | |
global using PC.Company.Project; |
This allows me to even further simplify my Program.cs file:
namespace Example | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
var product=new Product(); | |
ReadKey(); | |
} | |
} | |
} |