Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if condition with nullable

There is a lot of syntax sugar with Nullable<T> like those:

int? parsed to Nullable<int>

int? x = null
   if (x != null) // Parsed to if (x.HasValue)

x = 56; // Parsed to x.Value = 56;

And more.

Why if condition with Nullable doesn't work?

if (x)
{} 

It gets Complier error saying can't convert Nullable<bool> to bool.
Why it's not being parsed to if (x.HasValue && x.Value == true) or something similar?

It's the most obvious usage for Nullable<bool>

like image 910
gdoron is supporting Monica Avatar asked Jan 18 '12 14:01

gdoron is supporting Monica


People also ask

Can struct be nullable?

A struct can, however, be used as a nullable type in which case it can be assigned a null value."

How do you make a boolean nullable in C#?

bool b = null; c#

What is System nullable in C#?

A type is said to be nullable if it can be assigned a value or can be assigned null , which means the type has no value whatsoever. By default, all reference types, such as String, are nullable, but all value types, such as Int32, are not. In C# and Visual Basic, you mark a value type as nullable by using the ?


2 Answers

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.

like image 62
Eric Lippert Avatar answered Oct 24 '22 06:10

Eric Lippert


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.

like image 38
Jon Skeet Avatar answered Oct 24 '22 05:10

Jon Skeet