Skip to content

Top-level statements C# 9.0code reduction

Skip Program.Main() for a script-like experience.

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
  • args is available implicitly, and you can await or return an exit code
  • Because the functions are local, other types cannot call them
  • Taken further by file-based app directives C# 14.0

More information ​

Powered by Intracia