dotnet/roslyn

CS4014 compiler warning does not work when using null-conditional call operator

Open

#68,911 opened on Jul 7, 2023

View on GitHub
 (5 comments) (0 reactions) (0 assignees)C# (4,257 forks)batch import
Area-CompilersBughelp wanted

Repository metrics

Stars
 (20,414 stars)
PR merge metrics
 (Avg merge 6d 17h) (256 merged PRs in 30d)

Description

Description

The CS4014 compiler warning is raised when you call a task-returning method in an async context, but forget to await it.

We found by accident that if the ?. operator is used to call the method, the compiler warning does not flag this.

Reproduction Steps

The following code should reproduce the issue

using System;
using System.Threading.Tasks;

static class Program {

    static async Task Main(string[] args)
    {
        var worker = new Worker();
        // correct code
        await worker.DoSomething();
        await worker?.DoSomething();

        // incorrect code
        worker.DoSomething(); // Warning correctly raised here
        worker?.DoSomething(); // Expected Warning is not raised here. 

        await Console.Out.WriteLineAsync("All done");
    }
}

class Worker
{
    public async Task DoSomething()
    {
        await Task.CompletedTask;
    }
}

Expected behavior

I expect the warning to be raised when calling using ?.

Actual behavior

Warning is not raised

Regression?

No response

Known Workarounds

No response

Configuration

I tested it using Visual Studio 2022 professional targeting both the .NET 6 and .NET 7 SDK's (specifically 6.0.410 and 7.0.203 at time of writing)

Other information

No response

Contributor guide