Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resharper redundant 'else' really redundant?

Tags:

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?

like image 908
orourkedd Avatar asked Nov 14 '13 23:11

orourkedd


2 Answers

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; } 
like image 56
p.s.w.g Avatar answered Dec 11 '22 15:12

p.s.w.g


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.

like image 31
Noctis Avatar answered Dec 11 '22 15:12

Noctis