I am confused with c# compiler in case of negating the null
value of bool?
. Compiler does interpret !null
as null
. My expectation is to raise
CS0266 (Cannot implicitly convert type 'bool?' to 'bool')
Sample code:
bool? nullableVal = null;
//if (nullableVal) //OK: CS0266 bool? can't be converted to bool
// ;
var expectCS0266 = !nullableVal;//No compiler error/warning
//if ((!null) ?? false)//OK: CS8310 Operator '!' cannot be applied to operands of type "<NULL>"
// ;
if (! nullableVal ?? false)
;//this statement isn't reached, because of precedence of ! is higher than ??
//and !null == null
if (!(nullableVal ?? false))
;//this statement is reached, OK
Can somebody prove why the compiler is right or vice versa.