Top-level statements, introduced in C# 9.0, are a C# feature that lets you write executable program code directly in a source file (e.g. Program file) without explicitly creating a class and Main() method.
Definition: Top-level statements are executable statements written directly at the source-file level (outside any namespace or type declaration), which the compiler places into an automatically generated program entry method.
Because of Top-level statements features, instead of writing:
{
static void Main(string[] args)
{
Console.WriteLine("Hello, World!");
}
}
You can write:
Console.WriteLine("Hello, World!");
The compiler automatically generates the equivalent Program class and Main() method.
Conceptually, the compiler treats it like:
internal class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello, World!");
}
}
Characteristics of Top-level statements
- Only one file in your application can use top-level statements.
- The top-level statements cannot be enclosed in a namespace.
- When using top-level statements, the program cannot have a declared entry point i.e. Main() method. Other methods are allows except Main.
- Top-level statements still access a string array of args.
- The methods defined in the top-level statements file are local methods.
- Any types declared before the end of the top-level statements will result in a compilation error.
- Blocks are allowed to group executable statements in the top-level statements file.
Example. Type defined before top-level statements is invalid.
{
}
Console.WriteLine("Start");
Example. Type defined after top-level statements is valid.
class Employee
{
}
Example. Type defined before the end of top-level statement will throw error.