Top-level statements feature was introduced in C# 9 but is fully available in C# 10 with Visual Studio 2022. If you are a C# programmer, I am sure you remember importing all those common namespaces in your applications and having the Main method in the Program.cs. All of the default C# applications have that code.

The purpose of the top-level statements is to have simple and easy to understand/write code for beginners.

To understand this better, let’s look at the default template of simple C# console app prior to C# 9/10 and .NET 6. This was the default template to create a simple program.

using System;

namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
        }
    }
}


Listing 1.

If you look at this code, besides Console.WriteLine line of the code, rest of the code doesn’t do much but is just there. Each default program had a using statement, a namespace, a class and a static Main method. This is the entry point of a C# application.

Now, in .NET 6.0, C# 10, and Visual Studio 2022, the default console app template is this.

Console.WriteLine("Hello, World!");

Listing 2.

Both programs in Listing 1 and Listing 2 generates the exact same output and both are valid in C# 10, but Listing 2 offers the following advantage:

Depending on the project type, C# 10 and .NET 6.0 introduced implicit using directives, which the C# compiler automatically adds to the application. For console applications, the following directives are implicitly included in the application:

That means, if you need to use any classes and other objects from these namespaces, you do not need to import them in your .cs file.

It good to see that every new version of the C# language keep improving.

Cheers!