Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 222
Maxim Kitsenko Avatar asked May 30 '19 14:05

Maxim Kitsenko


3 Answers

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);
like image 75
canton7 Avatar answered Oct 18 '22 07:10

canton7


Async methods return a Task that can be awaited. If _user is null then you would not be returning a Task but null instead

like image 24
Dan D Avatar answered Oct 18 '22 07:10

Dan D


await is expecting a result. If _user is null then the result will be null, hence the NullReferenceException.

like image 27
Steve Todd Avatar answered Oct 18 '22 09:10

Steve Todd