When C# is executing instance-level code that belongs to an object, the keyword:
thisrefers to that current object.
If the current object is a particular Player, then:
thismeans that Player object.
If the current object is a particular Team, then:
thismeans that Team object.
The meaning changes with the object whose code is currently executing.
Suppose a UML object diagram contains:
Those can be different values because the objects are different.
This code:
Player player1 = new Player();creates a Player object.
The keyword:
thisdoes not create anything.
It only refers to the object whose instance-level code is already running.
Keep these ideas separate:
new
Creates an object.
this
Refers to the current object.
Sometimes C# allows a field to be referenced without writing this..
For example, inside the current Player object's code:
name = "Jordan";may refer to the current object's name field.
Writing:
this.name = "Jordan";makes the object ownership explicit:
This can be useful while learning object-oriented code because the relationship between the object and its member is visible.
Imagine code where a temporary value and a field have similar names.
A reference such as:
this.nameclearly identifies the field that belongs to the current object.
You do not need to redesign the supplied code to add this everywhere.
Read it when it appears and use it where the current course task calls for it.
When execution pauses inside instance-level code, the debugger can help you inspect the current object.
If you expand the current object, you may see fields such as:
name
jerseyNumber
isAvailableThose are the same members that expressions such as:
this.name
this.jerseyNumber
this.isAvailablerefer to.
The debugger makes the current object's state visible while this gives the source code a way to refer to that state.
When you see:
this.jerseyNumber = 7;read:
When you see:
this.isAvailable = true;read:
That reading keeps the object and the member connected.
this answers one important object-oriented question:
The answer is:
the current object.
The next activity focuses on the dot operator that connects an object reference such as this or player1 to one of its accessible members.