Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested if statements or not

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.

like image 229
Riain McAtamney Avatar asked Jun 17 '10 09:06

Riain McAtamney


4 Answers

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.

like image 153
Jon Skeet Avatar answered Nov 06 '22 06:11

Jon Skeet


You can check for true value even if it's null:

bool? val = null;
if( val == true ) // Works
{
  //do something
}
like image 21
simendsjo Avatar answered Nov 06 '22 05:11

simendsjo


What about:

if (boolIsAllowed ?? false)
{
}
like image 6
Philippe Leybaert Avatar answered Nov 06 '22 04:11

Philippe Leybaert


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
}
like image 1
AbstractCode Avatar answered Nov 06 '22 04:11

AbstractCode