Question

Simple code for example:

Object test=new Object();

I understand that memory for test object allocated into heap.

Quote from MSDN:

Variables of reference types store references to their data (objects)

But I really can't understand where stored this variable values (references to heap data), into stack or into heap or another place?

Was it helpful?

Solution

test variable is stored on stack - it holds address of object on heap. And object instance is stored on heap.

I suggest you to read .NET Type Fundamentals article by Jeffrey Richter:

When an object is allocated from the managed heap, the new operator returns the memory address of the object. You usually store this address in a variable. This is called a reference type variable because the variable does not actually contain the object's bits; instead, the variable refers to the object's bits.

In addition to reference types, the virtual object system supports lightweight types called value types. Value type objects cannot be allocated on the garbage-collected heap, and the variable representing the object does not contain a pointer to an object; the variable contains the object itself. Since the variable contains the object, a pointer does not have to be dereferenced in order to manipulate the object. This, of course, improves performance.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top