This is not to solve any particular problem. Simply a compiler question.
Why does the following code not result in compile error? It's comparing a reference type to primitive type. Both null and false have to to be interpreted into something for the compiler to do comparison. Or is the parser simply scanning for such pattern and replace it with false?
if(null == false) { }
It's legal because the lifted comparison operator is used. If you compare a bool
to a null
, both the bool
and null
get implicitly converted to Nullable<bool>
and the comparison operator for Nullable<bool>
ends up being used. You get a warning because obviously, it is always false.
Tejas's answer is correct. To more specifically address some of your points:
Why does the following code not result in compile error?
The question is not answerable; it does not produce an error because it is legal code, but that's a tautology.
If your question is actually "which section of the C# specification makes this legal?", then that's an answerable question. The section on lifted equality operators makes it legal.
It's comparing a reference type to primitive type.
It is not. First off, avoid the term "primitive type"; the specification does not clearly define it and it is not a useful concept in C#. You meant to say I think that it is comparing a value of reference type to a value of value type.
Second, that's not correct either. The null literal is not of reference type or value type; it is of no type. It is convertible to any nullable value type or any reference type, but it is of no type just by itself.
In this case the null literal is converted to the nullable bool type.
Both null and false have to be interpreted into something for the compiler to do comparison.
Correct. They are interpreted as nullable bools.
is the parser simply scanning for such pattern and replace it with false?
No, but that's an excellent guess. The compiler would constant-fold, say, true == false
down to false
, but it does not do folding optimizations that involve nullable value types. The language could be redesigned to support constant folding on operations with nullable value type operands; had nullable value types counterfactually been in version one, the proposed feature likely would have been supported.
Section 7.10.6 of the language specification (Reference type equality operators) states:
The
x == null
construct is permitted even though T could represent a value type, and the result is simply defined to be false when T is a value type.
This provision requires that null == false
be false
, and not a compiler error.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With