1.5.3 Calling Methods That Return Values

Overview

When a method returns a value, its call can appear where a value of that type belongs. For example, a Flight object can answer how many seats remain:

int seatsLeft = flight.GetAvailableSeats();

First, the method runs on flight. Its returned int becomes the value assigned to seatsLeft. If its capacity is 120 and 86 seats are booked, seatsLeft receives 34.

MainWindow calls Flight.GetAvailableSeats; Flight returns 34, which MainWindow stores as seatsLeft.
Store a Returned Seat Count
  • New
  • Changed
  • Removed

In this example, GetAvailableSeats needs no arguments. The caller still receives a result:

caller -> flight.GetAvailableSeats() -> Flight method runs
caller <- 34                      <- Flight method returns

An argument travels into a method. A return value travels back to the caller. They are not interchangeable.

Use the Returned Value

You can store the returned value for another statement to use:

int seatsLeft = flight.GetAvailableSeats();
MessageBox.Show(seatsLeft.ToString());

You can also use the call as part of an expression, as long as the surrounding code expects its type:

MessageBox.Show(flight.GetAvailableSeats().ToString());

Both examples display the integer returned by the Flight method. The first version gives the result a name, which can make it easier to inspect in the debugger or use again.

Read the right side of an assignment first:

int available = flight.GetAvailableSeats();

The call does not place a method inside available. It runs the method and puts the returned integer into available. If the Flight object's seat counts later change, the stored integer does not update itself; another call obtains a new result.

A Zoo's Animal object might return its age:

public int GetAge()
{
    return age;
}

The caller can store the result:

int animalAge = animal.GetAge();

The same pattern applies across objects: call the method on the intended object and use the result according to its declared type.

The call and its returned value are two parts of one interaction. A sequence diagram can show both the request to the Flight object and the answer sent back.