Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C# bool? x = true; if (x == true) looks awkward

Tags:

c#-4.0

bool? x = true;
if (x == true)

looks awkward.

But sometimes that is exactly what is needed.

Is there a better way?

EDIT:

Thank you all for the attempts, but so far I have not found a way that would beat the original. I guess I will just need to deal with awkwardness, perhaps comment it.

like image 852
Hamish Grubijan Avatar asked Dec 29 '22 05:12

Hamish Grubijan


2 Answers

Depending on your situation, you may want to use the null coalescing operator, which lets you specify the default value you'll use if the bool? is not set. It's not shorter than your conditional, but I think it's useful:

if(x ?? true) //defaults to true if x is not set

Or, to directly replicate your case (and due to popular demand):

if(x ?? false) //defaults to false if x is not set
like image 149
jball Avatar answered Jan 14 '23 14:01

jball


if (x) is equivalent to if (x == true). There is no need to make an extra comparison since x is a boolean value.

Edit: Missed that is was nullable. In that case, it really is the best you can get unless you want to make a simple helper function.

bool isTrue(bool? value) {
  return value == true;
}

But if (isTrue(x)) isn't much cleaner.

like image 24
unholysampler Avatar answered Jan 14 '23 16:01

unholysampler