You have already created objects and called methods such as:
team1.DisplayName();That statement asks the object referenced by team1 to run its DisplayName method.
An object can also call a method on another object that it can reach.
This is one of the basic ways objects cooperate inside a program.
Suppose the program has these two classes:
class Player
{
public Team team;
public void ShowTeamName()
{
}
}class Team
{
public string name;
public void DisplayName()
{
System.Console.WriteLine(this.name);
}
}The Player has a reference to a Team object.
At runtime:
Player player1 = new Player();
Team team1 = new Team();
team1.name = "Wildcats";
player1.team = team1;The objects are now related.
Inside Player, the ShowTeamName method can call the Team method:
public void ShowTeamName()
{
this.team.DisplayName();
}Read the statement from left to right:
Plain language:
In:
this.team.DisplayName();the receiver is:
When:
this.team.DisplayName();calls DisplayName, the current object inside DisplayName is the Team object.
So inside:
public void DisplayName()
{
System.Console.WriteLine(this.name);
}this.name refers to the Team's name.
The Player started the call.
The Team owns the method that is now executing.
That boundary is important.
Before the call:
current code is running on PlayerAfter entering DisplayName():
current code is running on TeamThe method call transfers execution into another object's behavior.
At this stage, method calls use:
The basic pattern is:
objectReference.MethodName();The important question is:
That question becomes central when you trace nested method calls next.