Mind-Bending Null-Check in Comparison Evaluation Can Be Improved

I have just noticed that nullables used in a comparison can be further checked to eliminate a false warning:

Where `Value` is `double?`:

    double? priorValue = Value;
   Value = null;
// ... (Re-compute Value here)
    return ((priorValue.HasValue != Value.HasValue)
            || (Value.HasValue
            && !CompareUnderTolerance(Value.Value, priorValue.Value));

Resharper warns that `priorValue.Value` might be null ... but it isn't.

0
4 comments

As a workaround, you could use:

&& !CompareUnderTolerance(Value.GetValueOrDefault(), priorValue.GetValueOrDefault()));

If you check the source, the only difference between Value and GetValueOrDefault is that Value checks the HasValue field, and throws an exception if it's false. Since you already know that both variables have a value, there's no point in checking it again.

0
Avatar
Permanently deleted user

In a simpler example, ReSharper is wrong:

Snippet

double? number;
...
if (number.GetValueOrDefault(0) == 0) {
} else
{
string s = $"{number.Value:#,##0}"; // ReSharper warns of null here
}

Using GetValueOrDefault implies that "number" is valid within the "else" block.

 

0

Hello!

 

Thank you for the feedback.

Please feel free to comment or vote for correspondent feature request - https://youtrack.jetbrains.com/issue/RSRP-468111

Thank you.

0

As a workaround for the string interpolation, you can drop the ".Value" without changing the output.

string s = $"{number:#,##0}";
0

Please sign in to leave a comment.