skip to content
Khalid Abuhakmeh logo Khalid Abuhakmeh

await at the top level

C# 9

C# top-level code awaiting an async SumAsync method and printing Total: 6.

Top-level statements await directly. No async Task Main. It is available since C# 9. The key line is var total = await SumAsync([1, 2, 3]) in async-main.cs. Run it and the output reads Total: 6. It fits in 8 lines; run it with dotnet run async-main.cs.

Did this tip save you some time? Consider sponsoring me on GitHub to fuel the next one.

Sponsor on GitHub
Railway Referral

Need somewhere to deploy?

My link gets you $20 in credits.

Claim $20 credit

I may earn a commission if you become a customer.

async-main.cs
var total = await SumAsync([1, 2, 3]);
Console.WriteLine($"Total: {total}");
static async Task<int> SumAsync(int[] xs)
{
await Task.Delay(10);
return xs.Sum();
}
Output
$ dotnet run async-main.cs
Total: 6