When text is null, text?.IndexOf(ch) != -1 is True?
Asked Answered
M

1

6

Observation: If text is null, this method returns True. I expected False.

return text?.IndexOf('A') != -1;

When I reflect the above line using ILSpy (or inspect the IL), this is the generated code:

return text == null || text.IndexOf('A') != -1;

Here is what I really need to meet my expectation:

return text != null && text.IndexOf('A') != -1;

Question: Does someone have a good explanation about why the Null Conditional code generated the OR expression?

Full Sample at: https://dotnetfiddle.net/T1iI1c

Mcnutt answered 7/6, 2016 at 0:51 Comment(0)
P
7

The line above really involves two operations: a null-conditional operator method call, and a comparison. What happens if you store the result of the first operator as an intermediate variable?

int? intermediate = text?.IndexOf('A');
return intermediate != -1;

Clearly if text is null then intermediate will also be null. Comparing this with any integer value using != will return true.

From MSDN (emphasis mine):

When you perform comparisons with nullable types, if the value of one of the nullable types is null and the other is not, all comparisons evaluate to false except for != (not equal).

This code can be written using the null-conditional operator as long as you can use a different operator to ensure a comparison with null evaluates to false. In this case,

return text?.IndexOf('A') > -1;

will return the output you expected.

Prehensible answered 7/6, 2016 at 1:29 Comment(1)
Thanks for that very good analysis and especially the MSDN bit. It's a good lesson to learn about comparing nullable types. Others at my work have been bitten by it as well.Mcnutt

© 2022 - 2024 — McMap. All rights reserved.