-
Garbage Collection in .NET Core
-
Garbage Collection (GC) is the memory management system built into the .NET runtime, Garbage Collection improves application reliability, reduces memory leaks, and prevents crashes caused by invalid memory access. By handling memory cleanup in the background, garbage collection allows developers to focus on building application logic while the runtime ensures memory is used responsibly.
What Is Garbage Collection?
Garbage Collection is the process of reclaiming memory occupied by objects that are no longer required or no longer reachable by the application. When an object loses all active references, it becomes eligible for cleanup and is eventually removed from the managed heap. Basically, it helps in reclaiming unused memory space
Example:void DisplayMessage() { string message = "Hello, .NET!"; }Once the method finishes, the
messagevariable goes out of scope. Since nothing references it anymore, the runtime marks it for garbage collection.
Managed vs Unmanaged Memory
Understanding garbage collection requires understanding the difference between managed and unmanaged resources.
Managed Memory
Managed memory refers to objects allocated within the .NET runtime and stored on the managed heap. The garbage collector fully controls this memory.
Examples include:- Objects
- Strings
- Arrays
- Collections
- Custom classes
var product = new Product();The runtime automatically tracks this object and frees it when it is no longer referenced. Developers do NOT manually release managed memory.
Unmanaged Memory
Unmanaged resources exist outside the runtime’s control and must be released explicitly.
Common examples:- File handles
- Database connections
- Network sockets
- Graphics handles
- OS resources
var stream = new FileStream("data.txt", FileMode.Open);The GC can clean the object eventually — but it does NOT guarantee when the file handle will be released.
IDisposable and Deterministic Cleanup
Garbage collection handles managed memory — but unmanaged resources must still be released manually.
The IDisposable interface provides a mechanism for deterministic cleanup.
Example: Using Statementpublic interface IDisposable { void Dispose(); }
When execution leaves the using block:using (var connection = new SqlConnection(connectionString)) { connection.Open(); }Dispose()is called automatically- The connection is released immediately
Without disposal, the resource might remain open until GC runs — which is unpredictable.
Generations in Garbage Collection
The .NET garbage collector uses a generational model to manage memory more efficiently. Instead of scanning the entire heap during every cleanup cycle, the runtime organizes objects into generations based on how long they survive. By focusing primarily on newer objects, the garbage collector reduces pause times and improves overall application performance.
Why Does Garbage Collection Use Generations?
Without generations, the runtime would need to inspect every object in memory during each collection cycle — an operation that would slow down applications considerably.
Generations improve efficiency by:- Prioritizing short-lived objects
- Reducing full heap scans
- Minimizing pause times
- Improving allocation speed
- Enhancing overall throughput
By concentrating cleanup efforts where they are most effective, the garbage collector maintains a balance between performance and memory availability.
Types of Generations in Garbage Collection
The managed heap is divided into three generations, each representing a different stage in an object’s lifecycle.
Generation 0 — Short-Lived Objects
Common Examples:- Temporary variables
- Method-level objects
- Loop allocations
- Short-lived data structures
Most of these objects become unreachable almost immediately, making them ideal candidates for Generation 0 cleanup. Frequent but fast collections keep memory usage under control.
Generation 1 — Medium-Lived Objects
Objects that survive a Generation 0 collection are promoted to Generation 1. This level acts as a transitional space between short-lived and long-lived objects.
Typical Examples:- Objects shared across multiple methods
- Temporary caches
- Data used during a workflow
var sessionData = new UserSession();If this object remains referenced during several operations, it survives early collections and moves into Generation 1.
Generation 2 — Long-Lived Objects
Generation 2 stores objects that persist for a significant portion of the application's lifetime. Because scanning large memory areas is expensive, collections in this generation are performed less frequently.
Common Examples:- Application-wide caches
- Static objects
- Singleton services
- Configuration data
public static ConfigSettings Settings = LoadConfiguration();Since this object is referenced throughout the application lifecycle, it eventually reaches Generation 2.
Final Summary
Garbage Collection is a cornerstone of the .NET runtime, automatically reclaiming unused managed memory while improving safety, stability, and performance. By combining generational cleanup with intelligent scheduling, the GC ensures efficient memory utilization without developer intervention.
However, understanding the distinction between managed and unmanaged resources — and using IDisposable when necessary — is essential for building scalable and reliable applications.