Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 893
Lee Grissom Avatar asked Jun 07 '16 00:06

Lee Grissom


1 Answers

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.

like image 78
BJ Myers Avatar answered Sep 20 '22 12:09

BJ Myers