Search code examples
c#exceptionasync-awaitnullreferenceexceptionnull-propagation-operator

await with null propagation System.NullReferenceException


I have the following code:

await _user?.DisposeAsync();

Visual Studio highlights this code, saying 'Possible NullReferenceException'

by the way, without await Visual Studio doesn't show this warning Why NullReferenceException is possible here?


Solution

  • await null will throw a NullReferenceException. Therefore if _user is null, then _user?.DisposeAsync() will return null, and the await will throw.

    You can do:

    if (_user != null)
    {
        await _user.DisposeAsync();
    }
    

    (you might need a local copy of _user if it might change between reads)

    or:

    await (_user?.DisposeAsync() ?? ValueTask.CompletedTask);
    

    (Prior to .NET 5, you will need:)

    await (_user?.DisposeAsync().AsTask() ?? Task.CompletedTask);