There is a lot of syntax sugar with Nullable
like those:
int? parsed to Nullable
int? x = null
if (x != null) // Parsed
Anything between the parentheses from the if-statement must evaluate to true or false. A nullable bool can evaluate to null, true or false.
I think that wouldn't be a good idea. That null
evaluates to false doesn't feel natural. Especially in if+else
statements. So forcing the user to be explicit with: if(nb==true)
and if(nb==false)
is a good idea IMO.
MSDN says:
bool? b = null; if (b) // Error CS0266. { }
This is not allowed because it is unclear what null means in the context of a conditional. To use a bool? in a conditional statement, first check its HasValue property to ensure that its value is not null, and then cast it to bool. For more information, see bool. If you perform the cast on a bool? with a value of null, a InvalidOperationException will be thrown in the conditional test.
http://msdn.microsoft.com/en-us/library/bb384091.aspx
Some of the answers to my question Why are there no lifted short-circuiting operators on `bool?`? touch on these aspects too
It's not that obvious that null should mean false. A null value means that the value is unknown or uninitialized. It's unknown whether the value is true or false. Who said null should behave like false?
A more obvious usage for Nullable<bool>
is to store something that can be either true or false, but sometimes is irrelevant or unknown, in which case the value is null.
Simply put, it fails to compile because the specification says it should - an if
condition requires a boolean-expression - and an expression of type Nullable<bool>
isn't a boolean-expression:
A boolean-expression is an expression that yields a result of type bool; either directly or through application of operator true in certain contexts as specified in the following.
However, it's easy to work round:
if (x.GetValueOrDefault())
{
}
Or to possibly be clearer:
if (x ?? false)
{
}
The latter approach is useful as it means you can easily change the behaviour if x
is null, just by changing it to x ?? true
.