Value types in object stored in heap as well?
I can imagine this question has been asked thousands of times, but I didn't have much luck in finding the answer, plus this is more out of curiosity than need.
Digging into the nuts and bolts of C#, I was wondering since objects are stored in the heap, are the value types within the objects stored in the heap as well or are they pl开发者_StackOverflow中文版aced in the stack?
Andrew Hare is right. For the full details, see Eric Lippert's blog entry:
I'm disturbed by the myth that "value types go on the stack" ... It is usually stated incorrectly: the statement should be "value types can be stored on the stack", instead of the more common "value types are always stored on the stack".
They are stored in the heap, inside of the memory allocated for the reference type. In addition, value types are often stored in places other than "the stack". However, the CLI spec does not specify where the memory pool that stores value types resides - it's an implementation detail that should not matter.
Those are stored on the heap, with the objects themselves. A good way to think about this is that when an object (that has value types as part of its state) is allocated on the heap, it's value types must live there as well, otherwise those value types would disappear as soon as the stack unwound for the code that created the object.
Yes, they're stored as part of the heap. However, it's all an implementation detail, as Eric Lippert has described on multiple occasions. I suggest you read his blog posts about it, this being the most recent one, and these two also being important.
精彩评论