#188 – Objects Are on the Heap, References to Objects Are on the Stack
December 22, 2010 5 Comments
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.
Pingback: #199 – You Can’t Explicitly Delete Heap-Based Objects « 2,000 Things You Should Know About C#
Pingback: #689 – References and Objects « 2,000 Things You Should Know About C#
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”
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.
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 ?