1.1.11 Referencing the Current Object With this

Video: This (11:01)
this Means the Current Object

When C# is executing instance-level code that belongs to an object, the keyword:

this

refers to that current object.

If the current object is a particular Player, then:

this

means that Player object.

If the current object is a particular Team, then:

this

means that Team object.

The meaning changes with the object whose code is currently executing.

Connect this to an Object Diagram

Suppose a UML object diagram contains:

Activity diagram showing this.name player1's name, then player2.name player2's name.
ThisNamePlayer1SName.
  • New
  • Changed
  • Removed

Those can be different values because the objects are different.

this Does Not Create an Object

This code:

Player player1 = new Player();

creates a Player object.

The keyword:

this

does 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.

this Can Make Ownership Explicit

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.

this Is Especially Helpful When Names Could Be Confusing

Imagine code where a temporary value and a field have similar names.

A reference such as:

this.name

clearly 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.

Follow this in the Debugger

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
isAvailable

Those are the same members that expressions such as:

this.name
this.jerseyNumber
this.isAvailable

refer to.

The debugger makes the current object's state visible while this gives the source code a way to refer to that state.

Read this as a Sentence

When you see:

this.jerseyNumber = 7;

read:

When you see:

this.isAvailable = true;

read:

That reading keeps the object and the member connected.

The Main Idea

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.