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:
this
↓
team
↓
DisplayName()
Plain language:
On the current Player object, follow its
teamreference to the Team object, then call that Team object'sDisplayNamemethod.
In:
this.team.DisplayName();
the receiver is:
this.team
That expression identifies the Team object whose method should execute.
This is different from:
this.DisplayName();
which would ask the current object to call a method on itself.
The object before the final dot matters.
A sequence diagram might show:
player1 : Player ── DisplayName() ──> team1 : Team
That communicates:
The Player object sends a
DisplayName()message to the Team object.
The C# statement:
this.team.DisplayName();
implements the same interaction when this.team refers to team1.
If:
this.team = null
then:
this.team.DisplayName();
cannot reach a Team object.
That can produce a NullReferenceException.
The call depends on the relationship already being established.
A useful sequence is:
create objects
↓
assign object reference
↓
call method on related object
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 Player
After entering DisplayName():
current code is running on Team
The method call transfers execution into another object's behavior.
If the Team already provides:
DisplayName()
then the Player can call that behavior.
Do not duplicate the same output logic inside Player merely to avoid an object-to-object call.
The method gives Team responsibility for its own behavior.
At this stage, method calls use:
The basic pattern is:
objectReference.MethodName();
The important question is:
Which object receives the method call?
That question becomes central when you trace nested method calls next.