Why are structs stored on the stack while classes get stored on the heap(.NET)?

(edited to cover points in comments)

To emphasise: there are differences and similarities between value-types and reference-types, but those differences have nothing to do with stack vs heap, and everything to do with copy-semantics vs reference-semantics. In particular, if we do:

Foo first = new Foo { Bar = 123 };
Foo second = first;

Then are “first” and “second” talking about the same copy of Foo? or different copies? It just so happens that the stack is a convenient and efficient way of handling value-types as variables. But that is an implementation detail.

(end edit)

Re the whole “value types go on the stack” thing… – value types don’t always go on the stack;

  • if they are fields on a class
  • if they are boxed
  • if they are “captured variables”
  • if they are in an iterator block

then they go on the heap (the last two are actually just exotic examples of the first)

i.e.

class Foo {
    int i; // on the heap
}

static void Foo() {
    int i = 0; // on the heap due to capture
    // ...
    Action act = delegate {Console.WriteLine(i);};
}

static IEnumerable<int> Foo() {
    int i = 0; // on the heap to do iterator block
    //
    yield return i;
}

Additionally, Eric Lippert (as already noted) has an excellent blog entry on this subject

Leave a Comment