C# 7.1 - Async Main has been around a while now

C# 7.1 has been out in the wild for quite a while (since August 2017 according to Wikipedia!) yet I still see a lot of people on Stackoverflow asking questions where they're hitting the .Result property of various calls to DoSomethingAsync methods because they're calling code from a Main method that isn't async, even though C# 7.1 provides support for having an async main method without having to write your own boilerplate to support it.

The docs.microsoft.com page What's new in C# 7.1 covers this quite adequately, however what it doesn't point out is that by default Visual Studio may not surface this for you. At least in Visual Studio 2017 (15.9.0) when creating a Console App (.NET FrameworK) targeting .NET Framework 4.7.1, this code won't compile:

class Program
{
    static async Task Main(string[] args)
    {
        var result = await GetNumber();
    }
}

The issue here is that the project is setup, by default, to use the C# latest major version which is 7.0 at the time of writing, meaning that the error being output from the C# compiler is:

Error CS5001 Program does not contain a static 'Main' method suitable for an entry point ConsoleApp1234

Fixing this is a simple matter of double clicking on the project in Solution Explorer to open its properties, choosing the Build page from the list on the left, clicking the Advanced... button at the bottom-right and then changing the Language version in the drop-down at the top of the window that appears to C# 7.1, or later:

Changing the language version for a project is a couple of clicks, but it does unlock being able to use async main without writing boilerplate code for it yourself

Once that's done, recompiling results in no compiler errors and an application that'll happily run. It's that simple.

About Rob

I've been interested in computing since the day my Dad purchased his first business PC (an Amstrad PC 1640 for anyone interested) which introduced me to MS-DOS batch programming and BASIC.

My skillset has matured somewhat since then, which you'll probably see from the posts here. You can read a bit more about me on the about page of the site, or check out some of the other posts on my areas of interest.

No Comments

Add a Comment