orourkedd
orourkedd

Reputation: 6421

Resharper redundant 'else' really redundant?

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?

Upvotes: 25

Views: 11530

Answers (3)

Noctis
Noctis

Reputation: 11783

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.

Upvotes: 7

p.s.w.g
p.s.w.g

Reputation: 149108

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;
}

Upvotes: 46

John3136
John3136

Reputation: 29266

It doesn't appear redundant to me. Removing the else would result in different program flow if both a and b are true.

Upvotes: 0

Related Questions