Why are there no lifted short-circuiting operators on `bool?`?

淺唱寂寞╮ 提交于 2019-11-27 20:09:53

What you propose would create two different usage patterns for nullable types.

Consider the following code:

bool? a = null;

// This doesn't currently compile but would with lifted true/false operators.
if (a)
{
}

// Whereas this provides a consistent use of nullable types.
if (a ?? false)
{
}

For consistency in the usage of nullable types, it makes sense to not lift the true and false operators on bool. I don't know if this is the real reason why it wasn't done, but it makes sense to me.

Since you showed that lifting true and false is technically possible, there are only two possible answers to your question (with "they" being the people who wrote the compiler/spec):

  1. It's an error in the spec, ie. they didn't think of this. (possible, but I doubt that)
  2. They thought that lifting the short-circuiting operators is potentially error-prone. It could be the same way of reasoning as why C# is completely class based (no sole functions as in C++) or why a statement like if (myNullVar) { ... } (with myNullVar being a reference) doesn't work in C# (but it does in C/C++).

I think there's always a balance between making a programming language more powerful and making it less error-prone.

Update: Just for you interest, that's what the official documentation says:

This is not allowed because it is unclear what null means in the context of a conditional.

Yanick Rochon

false && anything is the same as false. However if you expect false && anything to be true only if anything is false, then !anything is what you want.

Also, true || anything is the same as true. ...And I'm not sure how you could have it return false on any condition, as it would make no sense to have "this or that" return nothing!

... why adding additional weight to the condition when it's all clear and simple as it is?

I am not usually an adept of "because this is so", but I fail to see the advantage of adding such functionality.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!