In .NET, Value type object such as int is stored in memory.
Reference type object requires separate allocations of memory for the reference and object, and the object is stored in .NET object heap.
And Array is created in the heap, so how an array of value types such as int[] stored in the heap? Does it mean value type object can be stored in the heap without boxing?
Yes, you are right. I suggest you read this:
https://ericlippert.com/2010/09/30/the-truth-about-value-types/
It's very very good, and it explains nearly everything you'll ever want to know.
Yes, an array is one way in which a value type value can be stored on the heap without boxing. Another is just having it in a normal class:
public class Foo
{
int value1;
string name;
// etc
}
All the variables associated with an instance of Foo
are stored on the heap. The value of value1
is just the int
, whereas the value of name
is a string reference.
This is why the claim that "value types are stored on the stack, reference types are stored on the heap" is so obviously incorrect.
However, as Eric Lippert is rightly fond of pointing out, the stack/heap distinction is an implementation detail. For example, a future version of the CLR could store some objects on the stack, if it could work out that they wouldn't be needed after the method terminated.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With