1.7.4 Returning Object References From Methods

A Return Value Can Be an Object Reference

A method with return type `Player` returns a reference to a Player. The caller can store that reference and then use it to access the object.

Game field and caller result both lead to the existing Player.
Initial relationship
  • New
  • Changed
  • Removed
A Getter Can Return an Existing Player

A Game may already hold a Player in its `CurrentPlayer` field:

public Player GetCurrentPlayer()
{
    return CurrentPlayer;
}

The return value identifies that existing Player. The `return` statement does not create another Player.

The Caller May Now Share the Reference

After `Player selected = game.GetCurrentPlayer();`, `selected` and `game.CurrentPlayer` can reach the same object. Changing the Player through one path is visible through the other.

A Return Can Also Provide a New Player

A different method might return `new Player();`. That `new` expression creates a Player during the call. The returned reference lets the caller keep accessing it after the method ends.

Separate CreatePlayer calls return references to different Player objects.
How the relationship changes
  • New
  • Changed
  • Removed
The Type Does Not Specify Identity

Both methods have return type `Player`. Only the method's behavior tells whether the caller receives an old or a new object. Repeated calls to the getter may return the same Player; repeated calls that execute `new Player()` create separate Players.