This code compiles:
private static void Main(string[] args) { bool? fred = true; if (fred == true) Console.WriteLine('fred is true'); else if (fred == false) Console.WriteLine('fred is false'); else Console.WriteLine('fred is null'); }
This code does not compile.
private static void Main(string[] args) { bool? fred = true; if (fred) Console.WriteLine('fred is true'); else if (!fred) Console.WriteLine('fred is false'); else Console.WriteLine('fred is null'); }
I thought if(booleanExpression == true) was supposed to be a redundancy. Why isn’t it in this case?
There’s no implicit conversion from
Nullable<bool>tobool. There is an implicit conversion frombooltoNullable<bool>and that’s what happens (in language terms) to each of the bool constants in the first version. Thebool operator==(Nullable<bool>, Nullable<bool>operator is then applied. (This isn’t quite the same as other lifted operators – the result is justbool, notNullable<bool>.)In other words, the expression ‘fred == false’ is of type
bool, whereas the expression ‘fred’ is of typeNullable<bool>hence you can’t use it as the ‘if’ expression.EDIT: To answer the comments, there’s never an implicit conversion from
Nullable<T>toTand for good reason – implicit conversions shouldn’t throw exceptions, and unless you wantnullto be implicitly converted todefault(T)there’s not a lot else that could be done.Also, if there were implicit conversions both ways round, an expression like ‘nullable + nonNullable’ would be very confusing (for types that support +, like
int). Both +(T?, T?) and +(T, T) would be available, depending on which operand were converted – but the results could be very different!I’m 100% behind the decision to only have an explicit conversion from
Nullable<T>toT.