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 a script-like experience. The statements run as if inside Program.Main() while the functions that follow act as if part of the Program class.

Code

C#
Console.WriteLine("The answer is " + UltimateAnswer());

static int UltimateAnswer()
{
    return 42;
}
C#
static class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("The answer is " + UltimateAnswer());
    }

    static int UltimateAnswer()
    {
        return 42;
    }
}

More information