Volume 1 · Chapter 2 — Modern C# and .NET Foundations

.NET Memory Management

Goutham Mayaluri 7 min read .NETC#Memory

2.1 Why Memory Management Matters

Automatic memory management is one of the defining advantages of a managed platform: the CLR allocates objects on the managed heap and reclaims them through the garbage collector, freeing you from the manual allocate-and-free discipline of unmanaged languages. But “automatic” does not mean “ignore memory.” Poor object design, unnecessary allocations, unbounded caches, static references, large-object usage, and undisposed unmanaged resources all cause real production memory problems that the GC will not save you from. Understanding where memory lives and how it is reclaimed is essential to building stable, efficient services.

2.2 The Process Memory Model

A .NET process holds three regions relevant to engineers: the managed heap (objects, strings, arrays - reclaimed by the GC), the stack (per-thread method frames and local variables - reclaimed automatically as methods return), and native memory (OS handles, buffers, and anything the GC does not manage).

flowchart TB
  subgraph Proc["Application Process"]
      Heap["Managed Heap\n(objects, strings, arrays)\n-- reclaimed by GC"]
      Stack["Stack (per thread)\n(method frames, locals)\n-- reclaimed on return"]
      Native["Native Memory\n(OS handles, buffers)\n-- your responsibility"]
  end

2.3 Stack vs Heap

The stack is fast and automatic: allocations are just a pointer bump, and everything is reclaimed when the method returns. The heap is where reference-type objects live and is managed by the GC. Value types declared as locals live on the stack (or inline inside a heap object), while reference types always live on the heap with a reference to them stored wherever they are used.

Stack Heap
Very fast allocation (pointer bump) Managed and reclaimed by the GC
Stores value-type locals and references Stores reference-type objects
Automatic cleanup when the method exits Cleanup controlled by GC generations

2.4 Value Types vs Reference Types

Value types (int,bool,struct,enum) contain their data directly and are copied by value. Reference types (classes, arrays, delegates) store a reference to a heap object and are copied by reference. This distinction affects semantics, allocation, and performance.


int count = 10;                       // value type - data lives on the stack (as a local)
Customer customer = new Customer();   // reference type - object on heap, 'customer' is a reference

struct Point { public int X, Y; }     // value type - copied by value
class Node   { public int Value; }     // reference type - shared by reference

2.5 Boxing and Unboxing

Boxing wraps a value type in a heap-allocated object so it can be treated as a reference type; unboxing copies it back out. Each box is a heap allocation and a copy, so boxing on a hot path generates constant Gen 0 garbage. It happens explicitly when assigning a value type toobject, and implicitly through non-generic interfaces and collections - a common hidden cost.


int number = 100;
object boxed = number;      // Boxing - allocates on the heap and copies
int result = (int)boxed;    // Unboxing - copies back out

// Generics avoid boxing by specializing for value types:
List<int> fast = new();     // no boxing
System.Collections.ArrayList slow = new(); slow.Add(number);  // boxes every int

2.6 Deterministic Cleanup: IDisposable

The GC reclaims managed memory but does not deterministically release unmanaged resources - database connections, file handles, sockets, OS handles. Those implementIDisposableand must be disposed promptly, ideally withusing, which guaranteesDisposeruns even on exception.


await using var connection = new SqlConnection(connectionString);
await connection.OpenAsync(ct);
// Dispose (which closes the connection) runs automatically at the end of scope,
// even if an exception is thrown inside.
Senior Interview Question

Why can boxing hurt application performance?

Because each boxing operation allocates a new object on the managed heap and copies the value into it, and unboxing copies it back out. On a high-throughput path this generates constant Gen 0 garbage, which increases garbage-collection frequency and can cause pauses that show up as tail latency, and it adds an indirection. The danger is that boxing is often hidden - it happens implicitly when a value type flows through a non-generic interface or collection (likeArrayListorobjectparameters), in some string-formatting calls, and in LINQ over non-generic sequences - so it accumulates unnoticed. It is avoided by using generics (which specialize for value types without boxing), generic collections, and value-type-aware APIs. High-throughput services should profile allocations and eliminate boxing on hot paths.

Senior Interview Question

What is the difference between the stack and the heap, and what determines where an object lives?

The stack is a per-thread region storing method frames and local variables; allocation is a fast pointer bump and everything is reclaimed automatically when the method returns. The heap is where reference-type objects live and is managed by the garbage collector, which reclaims objects when they become unreachable. What determines where data lives is its type and context: reference types (classes, arrays, delegates) always live on the heap, with a reference to them stored wherever they are used; value types (structs, primitives) live where they are declared - on the stack when they are locals, or inline inside a heap object when they are fields of a class. Boxing is the exception that puts a value type on the heap. Understanding this matters because heap allocations create GC work while stack allocations do not, which is why low-allocation code favors value types and stack/inline data on hot paths.

Senior Interview Question

Why is IDisposable needed if the GC manages memory for you?

Because the GC managesmanaged memory, notunmanaged resources, and it runs non-deterministically. Things like database connections, file handles, sockets, and OS handles are scarce, expensive resources held outside the managed heap, and you cannot afford to wait an unknown amount of time for the next garbage collection to release them - you’d exhaust the connection pool or leak file handles.IDisposableprovides deterministic cleanup: you (or ausingstatement) callDisposeto release the unmanaged resource promptly, exactly when you are done with it, regardless of when the object’s memory is later collected. Relying on finalizers for this is a bug, because finalization is non-deterministic and actually keeps objects alive longer. The rule is: if a type owns an unmanaged resource, it implementsIDisposable, and callers dispose it withusing.

Principal Engineer Question

A payment service's memory grows steadily over days until it restarts. How do you find and fix it?

This is a managed “leak” - unintended retention - because the GC only collects unreachable objects, so something is keeping them reachable. I start with evidence, not code:dotnet-countersto confirm the managed heap is climbing without plateauing and Gen 2 is rising (distinguishing a managed retention problem from unmanaged handles or LOH fragmentation). Then I capture adotnet-gcdump(ideally two, spaced apart) from a live instance and diff object counts to see what is growing, and follow the retention path to the root holding those objects. The usual culprits are a static or singleton-held collection that grows forever, an event handler that never unsubscribes (pinning subscribers alive), or an unbounded cache. In this scenario a static dictionary cache without expiration is a classic cause. The fix targets the reference, not the memory: bound the cache with a size limit and expiration (or useIMemoryCache), unsubscribe inDispose, or clear the static collection. Then I add a regression guard - a heap-size alert or a soak test that watches for unbounded growth.

2.7 Production Scenario

A payment service shows steadily increasing memory over several days. A heap dump reveals millions of objects retained by a static dictionary used as a cache with no expiration or size limit - every entry ever added is still reachable, so the GC cannot reclaim it. The team replaces it with a bounded cache (size limit plus sliding expiration), adds a heap-size alert, and the memory plateaus.

Chapter Revision Notes

  • Managed memory is reclaimed by the GC; the stack is reclaimed automatically on return.
  • Reference types live on the heap; value-type locals live on the stack or inline.
  • Boxing allocates and copies - avoid it on hot paths with generics.
  • The GC does not release unmanaged resources - use IDisposable and using.
  • Managed leaks are unintended retention - fix the reference, not the memory.