There is a lot of syntax sugar with Nullable
like those:
int? parsed to Nullable
int? x = null
if (x != null) // Parsed
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
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
.