#188 – Objects Are on the Heap, References to Objects Are on the Stack

When you instantiate an object, an area of memory on the heap is allocated to store the object’s data.  So we typically say that the object is on the heap.

            Person thatGuy = new Person("Julius", "Caesar");

In the above example, a new instance of the Person class is created and the data for this Person is stored on the heap.

But in creating a new instance of a Person, we also had to declare and instantiate a reference to the Person object that we just created.  That reference is stored on the stack.

In the same way that value types are normally stored on the stack, but can be on the heap if they exist within another object, object references can also be on the heap if they are contained within other objects.

Advertisements

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

5 Responses to #188 – Objects Are on the Heap, References to Objects Are on the Stack

  1. Pingback: #199 – You Can’t Explicitly Delete Heap-Based Objects « 2,000 Things You Should Know About C#

  2. Pingback: #689 – References and Objects « 2,000 Things You Should Know About C#

  3. Cesar says:

    is this an error in the last line?

    “object references can also be on the heap (did you mean the stack?) if they are contained within other objects”

    • Sean says:

      Yes, you’re right. In the same way that stack-based value typed objects can also be on the heap when embedded in heap-based objects, stack-based object references can technically be on the heap when embedded within another heap-based object.

  4. Kunal says:

    So if I declare int Age = 25;
    So as per my understanding,
    1) If Age declared at Class leve: both reference(Age) and data (25) will go to heap.
    2) If Age declared withing some method: reference(Age) will go to stack and data(25) will go to heap.
    is this correct ?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: