What are top-level statements, and how do they simplify a basic C# program's entry point?
Short answer
Top-level statements (C# 9+) let you write executable code directly at the top of a .cs file WITHOUT wrapping it in an explicit Main() method or even a class — the compiler automatically generates the boilerplate Program class and Main method behind the scenes, reducing a…
Advertisement
AModel answer
Top-level statements (C# 9+) let you write executable code directly at the top of a .cs file WITHOUT wrapping it in an explicit Main() method or even a class — the compiler automatically generates the boilerplate Program class and Main method behind the scenes, reducing a minimal console app to just the code that actually matters.
// Program.cs -- entire program, no boilerplate needed
Console.WriteLine("Hello, World!");
var numbers = new[] { 1, 2, 3 };
Console.WriteLine(numbers.Sum());Real-world example
Writing a small utility script or a new minimal ASP.NET Core project's Program.cs without unnecessary ceremony.
Likely follow-ups
- Can you still access command-line arguments (the 'args' array) in a file using top-level statements?
Related topics