2.1.16 Passing a Returned Value as an Argument

Video: Don't Drop the Baby (8:22)
Overview

A method call can produce the argument for another method call. In Zoo, the Animal supplies a food portion and the vending machine uses that amount to calculate cost. The inner call runs first; its return becomes the argument passed to the outer call.

decimal foodCost = this.ComoZoo.AnimalSnackMachine
    .DetermineFoodCost(
        this.ComoZoo.FeaturedAnimal.GetPortionSize());
Send the Result to Another Method
Send the Result to Another Method. A method call can produce the argument for another method call.
Send the Result to Another Method
  • New
  • Changed
  • Removed

GetPortionSize() returns a double. DetermineFoodCost(double foodWeight) receives that returned double and produces a decimal price. The assignment stores that decimal in foodCost. The two calls are separate operations even though they appear in one statement.

The nested syntax does not reverse the call order. When a method call appears inside another call’s parentheses, its result must be available before the outer method receives its argument. A two-line version using foodWeight is often easier to debug, because you can pause between the calls and inspect the actual double being passed.

Trace the Outcome

First rewrite the statement using a local double foodWeight and check that the calls happen in the same order. If the types do not match the receiving parameter, C# requires a suitable conversion or a different method signature.