Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is an array of value types stored in .NET object heap?

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?

like image 531
superche Avatar asked Feb 23 '11 07:02

superche


2 Answers

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.

like image 171
xanatos Avatar answered Sep 19 '22 00:09

xanatos


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.

like image 21
Jon Skeet Avatar answered Sep 21 '22 00:09

Jon Skeet