There is a lot of syntax sugar with Nullable
like those:
int? parsed to Nullable
int? x = null
if (x != null) // Parsed
Technically it doesn't work because Nullable<T>
does not define a conversion operator to bool
.
Practically it is not supported for a variety of reasons, including:
Nullable<T>
?T
in Nullable<T>
-- how is that possible when you can plug in your own type as T
that the compiler knows nothing about?if(!x)
?It's the most obvious usage for
Nullable<bool>
Your "obvious" behaviour leads to many inobvious behaviours.
If
if(x)
is treated as false when x is null, then what should happen to
if(!x)
? !x
is also null when x is null, and therefore will be treated as false also! Does it not seem strange that you cannot reverse the behaviour of a conditional with an inversion?
What about
if (x | !x)
Surely that should always be true, but if x is null then the whole expression is null, and therefore false.
It is better to avoid these inobvious situations by simply making them all illegal. C# is a "make the user say what they mean unambiguously" language.
I believe that VB has the behaviour you want. You might consider switching to VB if this is the sort of thing you like.
It's the most obvious usage for Nullable
Be careful with statements like that. What seem obvious to you isn't necessarily what is obvious for some one else.
Furthermore,
if(x) {}
would also be illegal in case x was a reference type, so in the interest of consistency, the behavior should be the same for Nullables.
You can't do
if (x)
{...}
for the exact same reason you cannot write
int? a = null;
var b = a + 1;
A nullable boolean is not a boolean. In some cases, you want to consider a null bool? as true, and sometimes you want to consider it false. The language design does not make that decision for you.
Consider what whould happen in this case then
bool? nullBool = null;
if (nullBool)
{
someCode();
}
It would be impossible to tell if it entered the if senctence because the bool was null or false. That is probably not desirable
It's because a nullable bool cannot be implicitly converted to a bool. It's the same reason why you can do this :
int x1 = 7;
int? x2 = x1;
but you can't do this :
int? x1 = 7;
int x2 = x1;
you have to check before if it contains a value. Implicitly converting with nullable types can only be done when assigning a value, not when using that value.