Search code examples
c#c#-6.0null-conditional-operator

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


Solution

  • 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.