skip to content

Which static Main signatures does the C# compiler accept as a program's entry point, and what changes when Main is async Task<int>?

level: middleimportance: should knowfreq 50%

answer

  1. four return types, one optional parameter
  2. async only with a task
  3. the int becomes the exit code
  4. a synchronous candidate wins

basics

~20 s

A C# entry point is a static Main returning void, int, Task or Task<int>, taking nothing or one string[]. async is legal only on the task forms, and the compiler then adds a bridge that waits and returns the int as the exit code.

solid answer

~50 s

An entry point is a `static` method named `Main` in a class or struct, returning `void`, `int`, `Task` or `Task<int>`, with either no parameters or one `string[]`. Any access modifier works, and it is `private` when none is written. `async` is allowed only on the two task-returning forms (C# 7.1): `static async void Main` is error CS4009, and other shapes such as `ValueTask<int>`, `uint` or an extra parameter get warning CS0028 followed by error CS5001. For `async Task<int> Main`, the compiler emits a synchronous bridge method that the runtime calls; it runs your method, waits for the task and returns its result as the process exit code. With several candidates, a synchronous `Main` beats an async one (warning CS8892), and two valid synchronous `Main` methods, in one type or in two, are error CS0017 until the build names one.

code

csharp · 17 lines
csharp
namespace MigrationTool;

internal static class Program
{
    private static async Task<int> Main(string[] args)
    {
        if (args.Length == 0)
        {
            Console.Error.WriteLine("usage: migrate <target-version>");
            return 2;
        }

        await Task.Delay(50); // stands in for applying migration scripts
        Console.WriteLine($"migrated to {args[0]}");
        return 0;
    }
}

go deeper

for a junior

Recall the four return types, the optional string[] args parameter, and that returning an int sets the exit code a script can read.

for a middle

Explain why async is legal only with Task or Task<int>, what the generated bridge does, and how CS4009, CS0028 and CS5001 show up together in a build log.

for a senior

Diagnose multi-candidate builds: CS0017 for two valid synchronous Mains, CS8892 when a sync Main shadows an async one, CS7022 beside top-level statements, and keep exit codes a documented contract.

for a principal

Decide the exit-code contract for the team's command-line tools and make it visible by returning int or Task<int>, rather than relying on unhandled exceptions.

## The shapes the compiler accepts The **entry point** is the method the runtime calls first. Without top-level statements, C# looks for a method that meets all of these: - It is named exactly `Main` (`main` does not count) and is `static`. - It is declared in a class or a struct, and neither the method nor its containing type is generic. - It returns `void`, `int`, `Task` or `Task<int>`. - It takes no parameters, or exactly one `string[]` holding the command-line arguments (never `null`). - It may carry any access modifier; with none written it is `private`, and the runtime still finds it. That gives eight valid declarations, from `static void Main()` to `static async Task<int> Main(string[] args)`. The `async` modifier is optional on the task forms: a non-async `static Task<int> Main(string[] args)` that returns `Task.FromResult(4)` is an entry point too, and the process exits with code 4. ## What the compiler rejects, and how it says so | Declaration | Result with the .NET 10 SDK compiler | |---|---| | `static async void Main()` | error CS4009 "A void or int returning entry point cannot be async", then CS5001 | | `static ValueTask<int> Main()` | warning CS0028 "has the wrong signature to be an entry point", then error CS5001 | | `static uint Main()` or `Main(string[] args, int x)` | warning CS0028, then error CS5001 | | `static void Main()` inside `class Host<T>` | warning CS0402 "an entry point cannot be generic or in a generic type", then CS5001 | CS5001 reads "Program does not contain a static 'Main' method suitable for an entry point". The pattern matters when reading a build log: for a wrong return type, wrong parameters or a generic host, the specific problem is only a **warning**, and the build fails on the generic CS5001 that follows it. ## What `async Task<int> Main` turns into An async method returns its task at the first `await` that is not finished yet. If the runtime called that method directly and ignored the task, the process could end with work still pending. So the compiler adds a bridge: 1. Your `Main` is compiled like any async method, returning `Task<int>`. 2. The compiler emits a second, synchronous method (named `<Main>`, which C# cannot spell) and records it as the assembly's entry point. 3. The runtime calls the bridge; the bridge calls your `Main` and waits for the returned task to finish. 4. The task's `int` result becomes the **process exit code**; an exception from the task surfaces from the bridge as an unhandled exception. This is why `async void` is rejected: a `void` method hands back nothing to wait on. It is also why you never need `.Wait()` or `.Result` at the end of an async `Main`. ## When the project holds more than one candidate - Two valid synchronous `Main` methods, in one type or in several: error **CS0017**, "Program has more than one entry point defined. Compile with /main to specify the type that contains the entry point." The project's startup-object setting chooses one. - A synchronous and an async candidate, even in different types: the synchronous one wins and the async one gets warning **CS8892**, "Method ... will not be used as an entry point because a synchronous entry point ... was found." - Top-level statements in the project: they are the entry point, and any `Main` is ignored with warning **CS7022**. ## Findings worth raising in a review - A `static void Main` that blocks on an async helper with `.Wait()` or `.GetAwaiter().GetResult()`: switch to `async Task Main` and `await`, which also stops `.Wait()` from wrapping the failure in an `AggregateException`. - A `string[] args` parameter that nothing reads: it is optional and can go. - A second `Main` kept in a sample or helper class: harmless while its signature is invalid, CS0017 the day someone fixes it. - An exit status that depends on an exception escaping: return explicit codes so scripts see a value you chose. ## Exit codes in a command-line tool Shell scripts and CI steps read the exit code, so a tool such as a database migrator should return one deliberately: `0` for success and a documented nonzero value per failure class, such as `2` for bad usage. Returning `int` or `Task<int>` makes that contract visible in the signature, where `void` or `Task` would leave it to whatever an unhandled exception produces.

  • Why does `static async void Main` fail to compile when async void event handlers are allowed?
    An entry point must give the runtime something to wait on. A `void` method returns nothing, so the process could exit at the first incomplete `await`. The compiler reports CS4009, 'A void or int returning entry point cannot be async', and then CS5001 because no valid entry point remains. Return `Task` or `Task<int>`.
  • A class declares both `static void Main()` and `static async Task Main(string[] args)`. Which one runs?
    The synchronous one. The compiler reports warning CS8892, saying the async method will not be used as an entry point because a synchronous entry point was found, and builds the program around `void Main()`.
  • Does `Main` have to be `public`?
    No. `Main` may carry any access modifier and is `private` when none is written. The runtime starts at the method recorded as the assembly's entry point, so accessibility does not matter.

  • Main must be declared public static void Main(string[] args).
  • static async void Main works because the runtime waits for it.
  • A ValueTask<int> Main is a valid, allocation-free entry point.
  • With two Main methods the compiler just picks the first one.
  • An async Main needs .Wait() at the end to keep the process alive.