bool? nullableVar;
if(nullableVar)
gives me an error but
if(nullableVar==true)
evaluates fine.
Not sure I follow on why that is given that if the bool wasn't nullable would evaluate fine?
bool? nullableVar;
if(nullableVar)
gives me an error but
if(nullableVar==true)
evaluates fine.
Not sure I follow on why that is given that if the bool wasn't nullable would evaluate fine?
Writing if (nullableVar)
will try to implicitly convert the bool?
into a bool
. (Beause if
s require bool
s)
Since there is no implicit conversion from T?
to T
, you can't do that.
Note that you can also write
if (nullableVar ?? false)
The condition expression of an if
has to be implicitly convertible to bool
. Nullable<bool>
is not convertible to bool
, but the second expression is already of type bool
, so it's okay. Looking at the IL, I believe the second expression is really being compiled to:
if (nullableVar.GetValueOrDefault())
Nullable<T>
is only explicitly convertible to T
. In your case, your bool?
is only explicitly convertible to bool
. What you're trying to do here is an implicit conversion (an explicit conversion requires a cast to the desired type, whereas implicit does not).
Your comparison is an expression that results in a bool
, which is why it's allowed.
An if clause needs to be of a boolean type. Null is not a boolean type. By making the comparison, you are creating an expression with a result that is boolean.
a nullable bool can have 3 different values: true, false or null
bool? myNullableBool;
if (myNullableBool == false)
...
a non nullable bool can have only 2 values: true or false
bool myBool;
if (myBool)
...
Because ==
uses an Equals
overload call, whereas if()
expects the expression to be a bool
(or as Jon Skeet says implicitly convertible to bool
).
A bool?
(such as nullableVar
) can have three different values: true, false, or null.
if(nullableVar)
is ambiguous when nullableVar
is null.
if(nullableVar==true)
is clearly false when nullableVar
is null.