1.7.2 Mutating an Object Passed to a Method

An Object Parameter Can Reach the Caller's Object

When a Player is passed to a method, the method receives a reference value. The caller's variable and the method parameter can reach the same Player during the call.

Caller passes a Player to Game, which increments that Player during RecordTurn.
Initial relationship
  • New
  • Changed
  • Removed
Changing a Field Changes the Object

Suppose a Game method contains:

public void RecordTurn(Player participant)
{
    participant.NumberOfTurns++;
}

`participant` is a reference to a Player. The increment changes a field on that Player object.

The Change Remains After the Call

If `player.NumberOfTurns` was `0` before `game.RecordTurn(player);`, it is `1` afterward. The parameter variable stops existing when the call ends, but the Player and its changed field remain accessible through `player`.

Caller variable and method parameter both refer to the changed Player.
How the relationship changes
  • New
  • Changed
  • Removed
Repeated Calls Change the Same Player

Two calls with `player` as the argument increment that Player twice. Its `NumberOfTurns` becomes `2`; there is no automatic Player copy for either call.

Mutation Is Different from Reassignment

The statement `participant.NumberOfTurns++` changes the object. The statement `participant = new Player();` would instead change which object the parameter reaches. These statements have different effects on the caller's Player.