DEV Community

Cover image for Global using directives in dotnet 6 and C# 9+
Anil Kumar Khandei
Anil Kumar Khandei

Posted on • Updated on

Global using directives in dotnet 6 and C# 9+

The latest version of dotnet platform now supports global using directives which means we can now add all using directives in one place or 1 file instead of in every class file.

Infact all dotnet 6 project templates automatically include global directives option. In order to declare a global using directive, for example-

global using System;
Enter fullscreen mode Exit fullscreen mode

Now all files in the project can refer to all the api's in the System namespace.

Missing Main() method in Program.cs

Another significant change is when you try to create a new console application using visual studio or dotnet cli in dotnet 6 platform you see something like this-

Console.WriteLine("Hello, World!");
Enter fullscreen mode Exit fullscreen mode

Believe it or not thats the entire program.cs, it made me feel am I writing C# or JS on a browser console, the new C# 9+ evolution is mindblowing. So whats missing? To know that lets go back a bit, dotnetcore3.1 may be-

using System;

namespace dotnet5consoleapp
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

As you can see the using directive is missing, namespace, class program, Main method and last but not the least the curly brackets are missing. In case of dotnet6 the program entry is generated by the platform in the program.cs file which microsoft documentation terms as using "top-level statements". You can disable implicit using features from config file by removing the node <ImplicitUsings>enable</ImplicitUsings> from csproj file.

Now you can keep writing all your code in Program.cs file assuming as if you are writing within the Program class and Main method. This seems like less code but a bit confusing initially you can always refer to ms documentation for details.

Thanks for your time! Keep Learning!

Top comments (0)