The Program.Main() boilerplate can be unnecessarily verbose.
Top-level statements in C# 9 let you write code with a script-like experience. The statements run as if inside a compiler-generated Main method, and any functions declared alongside them are local functions of that method.
Code
csharp
Console.WriteLine("The answer is " + UltimateAnswer());
static int UltimateAnswer()
{
return 42;
}csharp
static class Program
{
static void Main(string[] args)
{
Console.WriteLine("The answer is " + UltimateAnswer());
}
static int UltimateAnswer()
{
return 42;
}
}Notes
- Only one file in a project can contain top-level statements, and they must come before any type declarations
argsis available implicitly, and you canawaitorreturnan exit code- Because the functions are local, other types cannot call them
- Taken further by file-based app directives C# 14.0