Search code examples
c#coding-stylefunction-exitnested-statement

Quick question about returning from a nested statement


If I have something like a loop or a set of if/else statements, and I want to return a value from within the nest (see below), is the best way of doing this to assign the value to a field or property and return that?

See below:

bool b;

public bool ifelse(int i)
{
if(i == 5)
{
b = true;
}

else
{
b = false;
}
return b;
}

Solution

  • Yes, that is good style.

    The alternative (which would be bad) would be to do this:

    
    public bool ifelse(int i) 
    { 
        if(i == 5) 
        { 
            return true; 
        }
        else 
        { 
            return false; 
        }
    }
    

    The reason multiple return points are regarded as bad style is that especially for larger methods it can be difficult to keep track of the program flow within a method because it could exit at any point. This can be a nightmare to debug. If you have a return variable that you assign to however, you can watch that variable and know exactly when it will be returned (from a single place).

    This isn't always the case, as with every stylistic point in programming there are good sides to it and bad sides.