简体   繁体   中英

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?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM