observation: if text null, method returns true. expected false.
return text?.indexof('a') != -1;
when reflect above line using ilspy (or inspect il), generated code:
return text == null || text.indexof('a') != -1;
here need meet expectation:
return text != null && text.indexof('a') != -1;
question: have explanation why null conditional code generated or expression?
full sample at: https://dotnetfiddle.net/t1ii1c
the line above involves 2 operations: null-conditional operator method call, , comparison. happens if store result of first operator intermediate variable?
int? intermediate = text?.indexof('a'); return intermediate != -1;
clearly if text
null intermediate
null. comparing any integer value using !=
return true
.
from msdn (emphasis mine):
when perform comparisons nullable types, if value of 1 of nullable types null , other not, comparisons evaluate false except != (not equal).
this code can written using null-conditional operator long can use different operator ensure comparison null evaluates false
. in case,
return text?.indexof('a') > -1;
will return output expected.