1.5.10 Writing Methods That Return on Every Code Path

Overview

An Animal method declared bool must provide a Boolean answer whenever it finishes normally. The compiler checks every possible route through the method. A void method can finish without providing a value; a bool method cannot. In the Zoo, pregnancy depends on whether the animal already has a Baby reference.

public bool GetIsPregnant()
{
    if (this.Baby != null)
    {
        return true;
    }
    else
    {
        return false;
    }
}

When Baby is non-null, the true branch returns true. When it is null, the else branch returns false. Both outcomes match the declared bool return type. The shorter return this.Baby != null; is equivalent, but the expanded version makes the two paths visible.

Check Both Return Paths
The two branches each reach a return. Removing the return false; statement would leave a path that ends without a Boolean result. The same check applies to methods returning int, double, decimal, or string. A bare return; is only appropriate in a voi
Check Both Return Paths
  • New
  • Changed
  • Removed

The two branches each reach a return. Removing the return false; statement would leave a path that ends without a Boolean result. The same check applies to methods returning int, double, decimal, or string. A bare return; is only appropriate in a void method.

Trace the Outcome

Trace the method with Baby == null and with a Baby object. Circle the return reached in each run. Before writing more complicated conditions, confirm that every path through a value-returning method ends with a value of its declared type.

For a method that returns a value after an if statement, a single shared return can also work when every branch assigns the same local variable first. This diagram uses a return inside each branch to make the compiler requirement obvious. A route that reaches the closing brace without a value is an error even if a person expects that route never to occur.