What is the stack and the heap, and what goes where in .NET?

.NET Framework & CLR Memory Basic Fresher1–2 Yrs Conceptual 1 min read

Quick Answer

The stack is a fast, per-thread region for method call frames — parameters, local variables, return addresses — freed automatically when the method returns. The heap is a shared region for objects (class instances, boxed values, arrays), managed by the garbage collector. Reference-type objects are always on the heap; the reference to them lives wherever it's declared.

The stack is per-thread and holds the call frames — locals, parameters, where to return to — and it's cleaned up automatically when a method returns. The heap is shared and holds objects, and the garbage collector manages it. The accurate statement is that reference-type objects are always on the heap; the reference variable pointing at one lives wherever it's declared. The “value types are on the stack” line is a simplification — an int field inside a class object is on the heap with that object, and a local captured by a lambda is on the heap too.

  • The common simplification “value types on the stack, reference types on the heap” is only half right: a value type that's a field of a class lives on the heap (inside that object); a captured local lives on the heap (in the closure).
  • What determines location is the variable's context, not just its type.
  • Stack allocation is essentially free; heap allocation costs GC pressure later.
  • Boxing moves a value type onto the heap.