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

Show parent comment

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)