In C# bool? x = true; if (x == true) looks awkward
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.
bool? x = true;
if (x.HasValue && x.Value)
{ /* Other code here */ }
or use GetValueOrDefault()
, but this is no terser...
bool? x = true;
if (x.GetValueOrDefault(false))
{ /* Other code here */ }
精彩评论