Possible Duplicate:
AND operation cannot be applied between nullable bools.
I would expect similar behavior like + or *. So if any of the operand is null, it should return null, but the compile complains if it's used in && or ||. Why?
To illustrate the point:
//this compiles
int? x = null;
int? y = null;
var z = x*y;
// this doesn't compile
bool? x = null;
bool? y = null;
if(x && y)
....
Annie Lennox - Why (Official Music Video)
Who Are You was the Who's last album to feature Keith Moon as their drummer, who died three weeks after it was released. The ironic nature of the text "Not to Be Taken Away" that was stencilled on Moon's chair on the album cover was noted by some critics.
If it were to return null
, then you invalidate the boolean requirement.
||
&&
Basically, it would allow for a value other than bool
(specifically, null
) within an if
statement which would be undefined behavior since if
statements require bool
ean expressions.
Interestingly, this is one of the areas where Java and C# differ. Java requires boolean values within the if
statement as well, but they allow their version of bool?
(Nullable<bool>
, or just Boolean
in Java) to be null
. This leads to somewhat unexpected NullPointerException
s at runtime, which C# is avoiding with this requirement.
Probably because && and || are short-circuiting operators. You can use & and | with bool? and I believe you get three-valued logic - null is treated as "unknown". So false & null is false, but true & null is null. This is confusing enough to keep track of, without throwing in short-circuiting too! It's possible that short-circuiting wouldn't actually be any use in the face of null values.
EDIT - On consideration, short-circuiting still makes sense for three-value logic. A logical AND with false on the left will always evaluate false, even if it has null on the right. A logical OR with true on the left will always evaluate true, even if it has null on the right. I imagine this is one of those "not worth the effort to implement" features. Sometimes you need short-circuited Boolean logic. Sometimes you need three-valued Boolean logic. But very rarely do the two overlap.
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