Understanding Top Level Programs
Learn about top-level programs in .NET 6: code generation, implicit imports, and revealing hidden compiler-generated code.
Top level programs
If we have seen older .NET projects before, we might have expected more code, even just to output a simple message. This is because some code is written for us by the compiler when we target .NET 6 or later.
If we had created the project with .NET SDK 5.0 or earlier or selected the check box with “Do not use top-level statements” label, then the Program.cs
file would have more statements, as shown in the following code:
using System; // Not needed in .NET 6 or later.namespace HelloCS{class Program{static void Main(string[] args){Console.WriteLine("Hello, World!");}}}
During compilation with .NET SDK 6.0 or later, all the boilerplate code to define a namespace, the Program
class, and its Main
method is generated and wrapped around the statements we write. This uses a feature introduced in .NET 5 called top-level programs, but it was not until .NET 6 that ...