All types are derived from the Object class, but the value types aren’t allocated on the heap. Value type variables actually contain their values. so how then can these types be stored in arrays and used in methods that expect reference variables ? Can somebody please explain me how these value types are stored on heap when they are part of an array?
-
[C# in Depth](http://www.manning.com/skeet/) is a good place to start. – naveen Jun 21 '11 at 07:27
-
1I think that array of value types is not value type by itself that's why it's stored in the heap like any composite objects. – Shadow The GPT Wizard Jun 21 '11 at 07:44
-
1Value types **can** be allocated on the stack, but it's not always the case... that's a common misconception – Thomas Levesque Jun 21 '11 at 07:51
-
+1 @Thomas Leveseque - this has become one of the biggest .NET programmer fallacies. I'd say in your average .NET application a good 50% of value types live in the heap.. – MattDavey Jun 21 '11 at 07:58
-
On the subject, see [this article](http://blogs.msdn.com/b/ericlippert/archive/2010/09/30/the-truth-about-value-types.aspx) by Eric Lippert – Thomas Levesque Jun 21 '11 at 08:02
4 Answers
Boxing and Unboxing. Also see Here for info pertaining to arrays specifically (part way down). Note this is for object arrays, a valuetype array (e.g. int[]
) doesn't have any (un)boxing.

- 31,770
- 9
- 95
- 162
Have a look at this question:
Arrays, heap and stack and value types
You can pass the instance of a value type to a method expecting an object (ref class). In this case boxing and unboxing happens.
Value type arrays do not require boxing or unboxing!
The CLR handles arrays of value types specially. Of course an array is a reference type which is allocated on the heap, but the value type values are embedded into the heap record (not on the stack).
Similarly, when a reference type class contains a value type field, the value of the field is embedded into the record on the heap..

- 8,897
- 3
- 31
- 54
-
Thanks a lot for replying. I guess I was knowing the answer just wasn't sure enough. – Chat Jun 21 '11 at 07:56
Value types may be allocated on stack. This can happen only if they are in parameters or local variables or fields in a another value type which is.
Value types in arrays and fields in classes are stored locally in array or class, instead of pointer being stored there - value types result in more local memory access (performance improvement) and in case of arrays value n is right after value n-1 in memory, something which is not guaranteed with objects in array of reference types (including boxed values in array of object - also no grantee of continuity). In arrays of reference types it is the references that are continual.

- 17,324
- 5
- 69
- 111