I hope this hasn't been asked before.
I have a nullable boolean called boolIsAllowed and a if condition like so:
if(boolIsAllowed.HasValue && boolIsAllowed.Value)
{
//do something
}
My question is this good code or would I be better separating it into a nested if statement? Will the second condition get checked if boolIsAllowed.HasValue is equal to false and then throw an exception?
I hope this question isn't too stupid.
Thanks in advance.
It's fine as is. The second condition won't be checked if HasValue
is false, so it won't throw an exception. It's like this sort of thing:
string name = ...;
if (name != null && name.Length > 5)
Again, that's fine - you won't get a NullReferenceException if name
is null, because && is short-circuiting.
Likewise the || operator is short-circuiting, but in the reverse way - there, if the left hand operand is true, the overall expression evaluates to true without checking the right hand operand. For example:
// Treat null as if it were an empty string
if (name == null || name.Length == 0)
EDIT: As noted in comments, this only applies to && and || - it doesn't apply to & and |, which always evaluate both operands.
You can check for true value even if it's null:
bool? val = null;
if( val == true ) // Works
{
//do something
}
What about:
if (boolIsAllowed ?? false)
{
}
More generally if you have a multiple conditions in your if statement consider extracting them into a method. This is not really necessary in this specific instance as some of the other answers have demonstrated. But it can be a lot simpler in more complex cases. Would you prefer to maintain:
if (taxApplied && taxValue > minimumTax && customerIsPreferred)
{
// Do something
}
or
if (CustomerGetsTaxRebate())
{
// Do Something
}
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