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? 
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);
                        Async methods return a Task that can be awaited.  If _user is null then you would not be returning a Task but null instead
await is expecting a result. If _user is null then the result will be null, hence the NullReferenceException.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With