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:
- It is much cleaner and the compiler in C# 10 assumes that code written in Listing 2 is the body part of the Main method.
- C# beginners find it much easy to get started and write their first application than getting confused with namespace and other keywords.
- The number of lines of code is much less and this can be compared to other popular frameworks that have similar templates.
- Implicit using directives makes sure that the using namespaces are already added without explicitly specifying them in the code based on the project type.
- The global using directive is used to define namespaces globally. That means, define in any one file or project file and the namespace is available to all classes in the project.
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:
- using System;
- using System.IO;
- using System.Collections.Generic;
- using System.Linq;
- using System.Net.Http;
- using System.Threading;
- using System.Threading.Tasks;
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!