Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why && and || cannot be used for nullable type? [duplicate]

Tags:

c#

.net

nullable

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)
    ....
like image 551
newman Avatar asked May 22 '11 22:05

newman


People also ask

Who is the singer of Why?

Annie Lennox - Why (Official Music Video)

Who are you Keith Moon?

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.


2 Answers

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 boolean 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 NullPointerExceptions at runtime, which C# is avoiding with this requirement.

like image 103
pickypg Avatar answered Oct 22 '22 14:10

pickypg


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.

like image 2
Weeble Avatar answered Oct 22 '22 14:10

Weeble