await结合空传播操作符为何触发VS的System.NullReferenceException警告?
await _user?.DisposeAsync() Triggers a Possible NullReferenceException Warning Great question—let's unpack exactly what's happening here:
The null-conditional operator (
?.) behavior: When_userisnull,_user?.DisposeAsync()doesn't throw right away—it simply returnsnull. That's the whole point of?.: it short-circuits property/method calls on null references to avoid immediate exceptions.The problem with
awaiting null: Theawaitoperator needs a valid awaitable object (likeTask,ValueTask, or a custom type implementing the awaitable pattern). If you passnulltoawait, the runtime tries to callGetAwaiter()on that null reference—and that's where theNullReferenceExceptionhits. You can't invoke a method on a null object, even implicitly viaawait.Why removing
awaitfixes the warning: Withoutawait, you're just evaluating the expression_user?.DisposeAsync()which returnsnullwhen_useris null—but you're not trying to do anything with that null value. There's no attempt to access members of a null instance, so Visual Studio doesn't see a risk of an exception here.
How to fix this safely
To avoid the potential exception while keeping the async disposal, rewrite the code to only await when _user isn't null:
if (_user is not null) { await _user.DisposeAsync(); }
Or if you prefer the older null check style:
if (_user != null) { await _user.DisposeAsync(); }
This ensures you only call DisposeAsync() and await it when _user is a valid, non-null instance, eliminating the null await scenario entirely.
内容的提问来源于stack exchange,提问作者Maxim Kitsenko

