Top-level statements

C# 9.0 .NET 5.0

Published Updated Author Jeffrey T. Fritz Reading time

Write C# code at the file level without wrapping in a class and Main method, making simple programs feel less boilerplate-heavy.

Top-level statements, introduced in C# 9.0 (.NET 5.0), allow you to write executable code directly in a file without wrapping it in a class and Main method. One file in your project can contain top-level statements; the rest must use traditional class-based declarations. This feature is especially useful for scripts, utilities, and learning code.

Why it matters

  • Reduces ceremony for simple console applications and scripts.
  • Makes learning C# easier by removing the need to understand classes and entry points upfront.
  • Improves readability of quick utilities and prototype code.
  • Aligns C# with scripting languages for rapid exploration.

Cautions

Only one file in a project can use top-level statements; the others must use traditional Main methods or classes. Top-level statements do not work in libraries (class libraries)—only in executable projects. If your program grows beyond a simple script, consider migrating to classes and methods for better maintainability.

Simplified hello world program

Top-level statements eliminate boilerplate for simple console applications, making the code more direct.

Valid since C# 9.0

Without var

using System;

class Program
{
    static void Main()
    {
        Console.WriteLine("Hello, World!");
    }
}

With var

Console.WriteLine("Hello, World!");

Script-like argument parsing

Top-level statements can access command-line args directly, making simple CLI scripts feel more natural.

Valid since C# 9.0

var name = args.Length > 0 ? args[0] : "World";
Console.WriteLine($"Hello, {name}!");
Console.WriteLine($"You provided {args.Length} argument(s).");

Learn more

Top-level statements (Microsoft Learn)