patterncsharpdotnetTip
Top-level statements: Program.cs without explicit Main method
Viewed 0 times
C# 9 / .NET 6+
top-level statementsminimal hostingProgram.csWebApplicationFactory partialno Main method
Error Messages
Problem
Prior to C# 9, every application required a Program class with a static Main method, adding boilerplate even for simple applications and making the hosting model harder to read.
Solution
Use top-level statements directly in Program.cs — no namespace, no class, no Main:
For integration tests that need access to Program, add a partial class declaration at the bottom:
// Program.cs
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddDbContext<AppDbContext>(opt =>
opt.UseSqlite(builder.Configuration.GetConnectionString("Default")));
var app = builder.Build();
app.UseHttpsRedirection();
app.MapControllers();
app.Run();For integration tests that need access to Program, add a partial class declaration at the bottom:
// Program.cs last line
public partial class Program { } // allows WebApplicationFactory<Program>Why
Top-level statements are syntactic sugar. The compiler wraps the code in a generated Program class with a synthetic Main method. This is identical at the IL level to the explicit form.
Gotchas
- Only one file per compilation unit can use top-level statements
- Local functions declared in top-level statements have access to args variable by default
- The generated class is internal — the partial class trick makes it accessible from test projects
Revisions (0)
No revisions yet.