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

Observation . If the text is null, this method returns True. I was expecting False.

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

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

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

Here is what I really need to meet my expectations:

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

Question : Does anyone have a good explanation of why Null Conditional code generated an OR expression?

Full example: https://dotnetfiddle.net/T1iI1c

+6
source share
1 answer

The above line actually involves two operations: calling the method of the null conditional operator and comparing. What happens if you save the result of the first statement 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 to any integer value with != Will return true .

From MSDN (highlighted by me):

When you perform comparisons with NULL types, if the value of one of the null types is null and the other is not, all comparisons are evaluated as false , except if = (not equal) .

This code can be written using a null condition operator if you can use another operator so that a comparison with a null value evaluates to false . In this case

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

will return the expected result.

+7
source

All Articles