1.1.26 Understanding Object References

A Reference Tells the Program Which Object to Use

When C# executes:

C#
Player player1 = new Player();

the variable player1 stores a reference that lets the code reach the new Player object.

Conceptually:

Plain text
player1 ──→ Player object

The reference is not the entire object.

It identifies which object the code should work with.

References Make Member Access Possible

When you write:

C#
player1.name

C# uses the reference in player1 to reach the Player object and then access its name member.

The path is:

Plain text
player1
   ↓
Player object
   ↓
name

If the reference is null, there is no Player object to continue through.

Object Fields Can Store References

Suppose a Player can refer to a Team:

C#
player1.team = team1;

Now the Player object contains a reference to another object.

Conceptually:

Plain text
player1 → Player object
              |
              | team
              v
         Team object ← team1

This is how object relationships can exist in runtime state.

A Reference Can Be null

A reference field may initially be:

Plain text
null

That means:

This reference does not currently identify an object.

For example:

Plain text
player1.team = null

does not mean the Player object is null.

It means the Player's Team reference is currently empty.

References Explain Nested Member Access

After:

C#
player1.team = team1;

the expression:

C#
player1.team.name

can be read as:

  1. use player1 to reach the Player;
  2. use the Player's team reference to reach the Team;
  3. access the Team's name.

Every reference step must lead to an object before the next member access can succeed.

References Connect UML and Runtime Memory

UML may show:

Plain text
player1 : Player -------- team1 : Team

C# may establish the connection with:

C#
player1.team = team1;

The debugger can then show the nested Team object through player1.

Three views describe one relationship:

Plain text
UML line
C# reference assignment
runtime object reference

Do Not Assume Assignment Copies the Whole Object

At this point, when you see:

C#
player1.team = team1;

understand it as assigning an object reference.

Do not picture all of the Team fields being copied into the Player.

The Player keeps a way to reach the Team object.

More detailed shared-reference behavior is taught later in PC1.

References Are Central to Object-Oriented Programs

They explain:

When an object relationship behaves incorrectly, tracing references is often the most useful place to begin.