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
HasValueis false, so it won’t throw an exception. It’s like this sort of thing:Again, that’s fine – you won’t get a NullReferenceException if
nameis 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:
EDIT: As noted in comments, this only applies to && and || – it doesn’t apply to & and |, which always evaluate both operands.