Where is the value type stored inside the class?

Possible duplicate:
Class fields, are they stored on the stack or heap?

If i have

Class A { int k=0; } 

and I do:

 A x = new A(); 

where is k stored? On the heap or on the stack? And why?

+4
source share
3 answers

This (possibly see below) stored on the heap, along with all other class data.

It is not stored on the stack, because there really is no point in placing it. Since the value is part of the reference type, it continues to live even after the current procedure exits. However, if it were on the stack, it would be deleted after the stack frame was inserted. This will cause the object to be invalid if some really monumental extra work is not done to try to shuffle it up and down the stack to save it.

In addition, the stack represents a small space and sticking each instance of each type of value ever created in the code will make it work very quickly.

However, the most correct answer is that the data storage location is an implementation detail, so you should assume that you do not know (and cannot). The real difference between reference and value types is built into their names: for value types, operations, such as assigning and passing as arguments, lead to copying the object. For reference types, such operations create an additional reference to the source object.

+2
source

Even if k is an int, which is a value type, it is contained in the reference type, so it will be stored on the heap as part of the memory allocated for x - although this is an implementation detail, this is the current behavior of .NET.

+6
source

There is no single answer. The CLR does not determine whether to put objects on the stack or heap.

For more information, read Eric Lippert blog posts.

+4
source

All Articles