1.7.5 Using Objects as Method Parameters

A Parameter Type Can Be a Class

A method can declare a `Player` parameter when its behavior depends on a Player object's state. The caller provides a Player reference as the argument.

Game receives a Player parameter and returns a description of its fields.
Initial relationship
  • New
  • Changed
  • Removed
One Object Groups Related Fields

A Player may hold both `Name` and `NumberOfTurns`. A Game method that describes a Player can read both fields through one parameter:

public string DescribePlayer(Player participant)

The signature says that the method accepts a Player and returns a string. Inside the method, `participant.Name` and `participant.NumberOfTurns` refer to fields on that Player.

One Method Works with Different Players

A call with Jordan's Player reads Jordan's fields. A later call with Casey's Player reads Casey's fields. The method definition stays the same; the argument changes which object the parameter reaches.

Several Parameters Can Be Object References

A method can receive two Player references:

public bool HasMoreTurns(Player first, Player second)

The first and second arguments supply those parameters in order. They may refer to different Players, or they may both refer to one Player.

Same Object Arguments Share State

If both arguments identify the same Player, `first.NumberOfTurns` and `second.NumberOfTurns` read the same field. A comparison using `>` between those readings is false.

Null Is Not an Object

A Player parameter can contain `null`. Reading `participant.Name` in that case throws a `NullReferenceException`, because no Player object is available through the parameter.

Two Player parameters can both refer to the same Player object.
How the relationship changes
  • New
  • Changed
  • Removed