Resharper is telling me that the 'else' in this code is redundant:
if(a) { //Do Something } else if(b) { //Do Something }
The else
does not seem redundant because the else
keeps b
from being evaluated if a
is true. The extra overhead is small if b
is a variable, but b
could also be an expression.
Is this correct?
It's redundant if you have a some sort of break
, continue
, return
, or throw
statement (or even a goto
) inside the first if
-block that always causes execution to branch outside the current block:
if(a) { return 0; } else if(b) { return 1; }
In this case, if the code enters the first block, there's no way it will enter the second block, so it's equivalent to:
if(a) { return 0; } if(b) { return 1; }
You are right in this case, but this is the reason I think they had it to begin with:
Certain if-else conditions can have their else clause removed. Consider the following method:
public int Sign(double d) { if (d > 0.0) return 1; else return -1; }
In the above, the else statement can be safely removed because its if clause returns from the method. Thus, even without the else, there’s no way you’ll be able to proceed past the if clause body.
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