Best Way to Check for Nullable Bool in a Condition Expression (If ...)

Best way to check for nullable bool in a condition expression (if ...)

I think a lot of people concentrate on the fact that this value is nullable, and don't think about what they actually want :)

bool? nullableBool = true;
if (nullableBool == true) { ... } // true
else { ... } // false or null

Or if you want more options...

bool? nullableBool = true;
if (nullableBool == true) { ... } // true
else if (nullableBool == false) { ... } // false
else { ... } // null

(nullableBool == true) will never return true if the bool? is null :P

nullable bool in if() statement - checks required?

Actually I don't recommend you to treat null as false. Either use non-nullable boolean, or explicitly handle null value. One more option to do that:

if (foo ?? false)
{

}

Conditional expression with nullable bool produces compiler error

This should work :

return !PassChecked && !FailChecked ? null :
PassChecked ? (bool?)true : (bool?)false;

C# null or null-conditional operator in boolean expression

As Rofus and Jeroin correctly pointed out in comments the conversion between T to T? is always implicit when you do the comparison with "Null" 7 becomes a "Nullable<int>"

bool bar = foo?.Count > 7;

is similar to -

 int? count = null; 
int? k = 7; // Implicit conversion here!
var bar = count > k;

For your second question on the > operator. Yes, while the Nullable<T> struct does not define operators such as <, >, or even ==, still the following code compiles and executes correctly which is similar to your case -

int? x = 3;
int? y = 10;
bool b = x > y;

This is because compiler lifts the greater than operator from underlying value type like -

bool b = (x.HasValue && y.HasValue) ? (x.Value > y.Value) : false;

Operator Lifting or Lifted Operators means you can implicitly use T's operators on T?. Compiler has different set of rules on different set of operators on handling them on Nullable<T> types.

checking if a nullable bool is null or not

if (!nullableBool.HasValue)
{
// null
}

You also can directly compare it with null.

Using null-conditional bool? in if statement

An if statement will evaluate a Boolean expression.

bool someBoolean = true;

if (someBoolean)
{
// Do stuff.
}

Because if statements evaluate Boolean expressions, what you are attempting to do is an implicit conversion from Nullable<bool>. to bool.

bool someBoolean;
IEnumerable<int> someList = null;

// Cannot implicity convert type 'bool?' to 'bool'.
someBoolean = someList?.Any();

Nullable<T> does provide a GetValueOrDefault method that could be used to avoid the true or false comparison. But I would argue that your original code is cleaner.

if ((list?.Any()).GetValueOrDefault())

An alternative that could appeal to you is creating your own extension method.

public static bool AnyOrDefault<T>(this IEnumerable<T> source, bool defaultValue)
{
if (source == null)
return defaultValue;

return source.Any();
}

Usage

if (list.AnyOrDefault(false))

use ternary operator to get value of nullable bool in C#

Depends on how you want someNullableBool to be interpreted if it's null.

If you want null to be treated like either true or false, you can say (someNullableBool ?? valueIfNull) to treat it like one or the other.

If null has to be handled specially, then you'll need to check someNullableBool.HasValue and handle the case where it's null. Once you've done that, the case for true and false can be handled as above.

If the value should never be null, ideally it shouldn't be a nullable in the first place. :P But if that's out of your control, you might want to cast to bool or use the nullable's Value property to make that expectation explicit, and to fail if ever it doesn't hold.

Use of Boolean? in if expression

You can compare nullable boolean with true, false or null using equality operator:

var b: Boolean? = null
if (b == true) {
// b was not null and equal true
}
if (b == false) {
// b is false
}
if (b != true) {
// b is null or false
}

if condition with nullable

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.



Related Topics



Leave a reply



Submit