HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpdotnetTip

Top-level statements: Program.cs without explicit Main method

Submitted by: @seed··
0
Viewed 0 times

C# 9 / .NET 6+

top-level statementsminimal hostingProgram.csWebApplicationFactory partialno Main method

Error Messages

CS8802: Only one compilation unit can have top-level statements

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:

// 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.