1.1.24 Understanding Object Memory

Objects Exist in Memory While the Program Runs

When C# executes:

C#
Player player1 = new Player();

the new Player() expression creates a Player object in memory.

The object can contain state such as:

Plain text
name
jerseyNumber
team

The exact fields come from the supplied class.

At this stage, think of memory as the working space used by the running program.

A Reference Gives Code Access to an Object

After:

C#
Player player1 = new Player();

the name player1 gives the code a way to reach the new Player object.

A useful conceptual picture is:

Plain text
player1
   |
   v
+------------------+
| Player object    |
| name             |
| jerseyNumber     |
+------------------+

The reference and the object are related, but they are not the same thing.

The Object Holds Its Fields

Suppose the code then executes:

C#
player1.name = "Jordan";
player1.jerseyNumber = 7;

Conceptually, the state can be pictured as:

Plain text
player1
   |
   v
+----------------------+
| Player object        |
| name = "Jordan"      |
| jerseyNumber = 7     |
+----------------------+

The values belong to the object.

The reference gives the program access to that object.

Related Objects Are Separate Objects

Now create a Team:

C#
Team team1 = new Team();
team1.name = "Wildcats";

There are now two objects in memory:

Plain text
player1 → Player object
team1   → Team object

If the Player should refer to the Team:

C#
player1.team = team1;

the objects remain separate. A reference connects them.

Conceptually:

Plain text
player1 → Player object ──team──→ Team object ← team1

Memory Is Different from a UML Diagram

A UML object diagram is a model.

The runtime memory is the actual state created by the executing program.

The UML may show:

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

C# instructions create those objects and relationships.

The debugger lets you observe the runtime version.

Memory Is Also Different from a File

If the program closes, its normal runtime objects do not remain alive in memory as the same running objects.

Persistent storage is a separate concept.

Do not confuse:

Plain text
object exists in current program memory

with:

Plain text
information has been saved to a file

The Debugger Gives You a Window into Memory

Visual Studio does not show every low-level hardware detail.

It gives you a useful programming view:

That is enough to reason about the object model at this stage.

Avoid Over-Interpreting the Picture

Conceptual boxes and arrows help you reason about objects.

They are not literal diagrams of physical RAM addresses.

The important relationships are:

Later modules explore shared references more deeply.

For now, use memory as the place where the running program's object state exists.