#234 – Multiple return Statements

You can have more than one return statement in a method and they can appear anywhere in the method.  If the return type of the method is not void, you must have at least one return statement and all return statements must return a value of the appropriate type.

It’s normally considered good practice to have a single return statement at the end of the method, to make the code more readable.  But you could also do something like the following:

        public float GiveAgeInHumanYears()
            if (Age < 1)
                return 0;
            else if (Age == 1)
                return 10.5f;
                return 21 + ((Age - 2) * 4);

#160 – A while Loop Can Exit on break, goto, return or throw Statements

In addition to completing normally, when the loop expression evaluates to false, a while loop can exit early.  A loop will exit early if it encounters one of the following statements: break, goto, return or throw.

A break statement causes an early exit of the loop and execution to continue with the first statement after the loop.

            uint numTimes = 0;
            while (numTimes < 100)
                WriteOnBlackboard("I will not eat paste");
                if (ChalkBroke())
                    break;     // Stop writing

The goto statement can transfer control out of a while loop, to a labeled statement.  Its use is rare, since there are generally more elegant ways to transfer control.

The return statement can transfer control out of a loop and return control to the calling method.

The throw statement transfers control out of a loop and throws an exception, indicating that an error condition occurred.