1.1.26 Understanding Object References

A Reference Tells the Program Which Object to Use

When C# executes:

Player player1 = new Player();

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

Conceptually:

Object diagram showing player1, then Player object, then name.
Player.
  • New
  • Changed
  • Removed

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:

player1.team = team1;

Now the Player object contains a reference to another object.

Conceptually:

Object diagram showing player1 Player object, then team, then v, then Team object ← team1.
Player1PlayerObject.
  • New
  • Changed
  • Removed

This is how object relationships can exist in runtime state.

A Reference Can Be null

A reference field may initially be:

null

That means:

For example:

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:

player1.team = team1;

the expression:

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:

player1 : Player -------- team1 : Team

C# may establish the connection with:

player1.team = team1;

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

Three views describe one relationship:

UML line
C# reference assignment
runtime object reference
Do Not Assume Assignment Copies the Whole Object

At this point, when you see:

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:

  • how code reaches objects;
  • how objects can be connected;
  • why nested member access works;
  • why null can cause runtime exceptions.

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