Tuesday, June 09, 2009

Heap vs. Stack – where does your data reside?

I keep mixing it up between heap and stack, so this post is more of a reminder for me.

Value types go in one container and Reference types go in the other.

Typically value types go into the Stack and reference types go onto the Heap.

Why do I say typically? Because value types that are declared as part of a reference type (members) are stored on the heap.

A more specific rule:

Reference types are always allocated on the Heap.

Value types and pointers are allocated on the Stack if they were defined within a method. But if they (value types and pointers) were declared as member variables of a class (a reference type), then they get allocated on the Heap.

Here is a good article that touches on these issues and more: Heaping vs. Stacking

2 comments:

  1. Additional commentary from Eric Lippert's Blog:
    part 1
    part 2

    ReplyDelete
  2. The relevant feature of value types is that they have the semantics of being copied by value. Similarly, the relevant feature of reference types is that they have the semantics of being copied by reference.

    ReplyDelete

Remember, if you want me to respond to your comment, then you need to use a Google/OpenID account to leave the comment.