"Possible System.NullReferenceException" when using Null Conditional Operator

Hello, I'm seeing some weird behavior with the  R# warning "Possible System.NullReferenceException"

HttpResponseMessage result = await Client.Post(url, value);
var resultContent = await result.Content?.ReadAsStringAsync();

I'm getting the warning on the result.Content property where I'm explicitly checking for null with the null-conditional operator '?.'

If I remove the operator then the warning goes away. So I'm not really sure what's happening here? Any advice or comments appreciated.

R# version 2019-05-01, VS version 14.0.25431.1

0
3 comments

The warning is correct - if result.Content is null, then you're trying to await a null Task, which will throw a NullReferenceException.

1
Avatar
Permanently deleted user

Ah, so when I remove the "?." R# is no longer able to detect if it will be null so it just doesn't show the warning, is that correct? Content can still hypothetically be null but R#'s null detection is just not able to accurately discover that.

Also thank you, learned something today.

0

By default, the "value analysis mode" is set to "optimistic":
https://www.jetbrains.com/help/resharper/Reference__Options__Code_Inspection__Settings.html

Therefore, if you don't test whether the Content property is null, R# assumes it's not.

https://www.jetbrains.com/help/resharper/Code_Analysis__Value_Analysis.html

1

Please sign in to leave a comment.