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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With