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

FireSnake picture FireSnake · Apr 20, 2010 · Viewed 132.7k times · Source

I was wondering what was the most clean and understandable syntax for doing condition checks on nullable bools.

Is the following good or bad coding style? Is there a way to express the condition better/more cleanly?

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

especially the if (nullableBool ?? false) part. I don't like the if (x.HasValue && x.Value) style ...

(not sure whether the question has been asked before ... couldn't find something similar with the search)

Answer

Artiom Chilaru picture Artiom Chilaru · Apr 20, 2010

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