C# › Memory & Garbage Collection

What is the difference between the stack and the heap in .NET memory management?

Beginner

Answer

The stack stores value-type local variables and method call frames, with fast, automatic, LIFO-ordered allocation/deallocation tied to method scope; the heap stores reference-type objects (and boxed value types), with allocation managed by the .NET runtime and deallocation handled by the garbage collector, not tied to any particular method's scope.
void Method() {
  int x = 5;              // value type: allocated on the stack
  var person = new Person(); // reference type: 'person' variable on stack, actual object on the heap
} // 'x' and the 'person' reference are popped off the stack when Method() returns
Real-world example Understanding why a local int variable is instantly reclaimed on method return, while a 'new Person()' object survives until the GC decides to collect it.

Common follow-ups: Why can objects on the heap potentially survive LONGER than the method call that created them?