For 20 years, every C# console application started with the same ceremony: namespace, class Program, static void Main(string[] args). C# 9.0 and .NET 5 change this with Top-level programs.
The Change
Here is the “Hello World” of the past:
using System;
namespace MyApp
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
}
Here is C# 9:
using System;
Console.WriteLine("Hello World!");
How It Works
The compiler essentially wraps your top-level code into a generated Program class and Main method for you. You can still access command-line arguments via the magic `args` variable:
Console.WriteLine($"Hello {args[0]}");
return 0; // Return exit code
Beyond “Hello World”
This isn’t just for learning. It’s great for microservices, Azure Functions (isolated process), and utility scripts. It removes visual noise and lets you focus on the logic. You can define methods and local functions right in the file, or import other classes as usual.
This feature lays the groundwork for the “Minimal API” patterns we expect to see grow in ASP.NET Core in the future, where setting up a web server could be done in just a few lines of code.
Discover more from C4: Container, Code, Cloud & Context
Subscribe to get the latest posts sent to your email.