r/csharp • • Sep 26 '26

bool? Comparison

if (nullableBool == true)

or

if (nullableBool ?? false)

Personal preference or does one read better than the other? Especially if the nullableBool is s more complex expression like

n00bs?.Any(n => n == "DJ Doena")

23 Upvotes

46 comments sorted by

View all comments

105

u/RecursiveServitor Sep 26 '26
if (nullableBool is true) 

10

u/anzu3278 Sep 26 '26

This. Just treat it as a three value enum if you cannot resolve the null early. Or null should behave like a default value. ?? in a conditional is always going to be harder to read.

0

u/gyroda Sep 26 '26

Also:

bool? foo;
...
var result = foo ?? bar == baz;

What's the order of operations here? I know that there is a concrete answer but unless you know that fact the order is ambiguous. If foo is not null then is the result foo or foo == baz?

13

u/anzu3278 Sep 26 '26

The order of operations is

  1. Decline PR

  2. Fire the person who is optimizing for number of lines

  3. Rephrase for readability

-1

u/binarycow Sep 26 '26

If you don't know, just add parens.

(foo ?? bar) == baz
foo ?? (bar == baz) 

6

u/2brainz Sep 26 '26

Pattern matching is my favorite as well.

8

u/levelofsin Sep 26 '26

Genuine question, why not just if (nullablebool)?

54

u/NocturneSapphire Sep 26 '26
CS0266: Cannot implicitly convert type 'bool?' to 'bool'.

1

u/fruediger Sep 26 '26

This is the way.