Search⌘ K
AI Features

Garbage Collector

Learn how the C# garbage collector automatically manages memory for reference types, including object lifecycle across generations and heap compaction. This lesson explains how garbage collection works, focusing on the System.GC class, memory generations, and when to manually invoke garbage collection for optimized application performance.

There is a significant difference in how value and reference types are stored in memory. When we create a local value-type variable, the value behind the variable is stored on the method stack. However, if a value type is a member of a class, it is stored on the heap along with the object. When the method finishes running, the stack is cleared.

Local reference-type variables are also stored on the stack, but the variable contains the memory address of the region in the heap where the object is actually stored.

When a method finishes running, reference-type variables are immediately ...