开发者

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

This question already has answers here: Closed 11 years ago.

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 illust开发者_开发知识库rate 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)
    ....


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.


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.


Even if (x && y) was possible, result would be bool? and not bool. If () only works with bool.

Try if (((bool)(x ?? false)) && (bool)(y ?? false)) instead.

Or better yet, following weebles' answer:

If (x & y == true).


Nullable types are actually objects. When you apply the nullable operator '?' to a value type (such as bool), it becomes a reference to an object that holds either "null", or the value of the underlying value type.

Consider this:

bool? isActive;

This actually becomes:

Nullable<bool> isActive;

The value type actually becomes an object instance, and therefore doesn't participate in boolean expressions as regular value types do.

More info: http://msdn.microsoft.com/en-us/library/1t3y8s4s.aspx

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜