New Batch Starts 1st September 2025 – Join Our .NET Full Stack Development Course, Daily 6-8 AM and 8.30-10.30 PM, Register Now
+91 9989950088
info@example.com

🗑️ Garbage Collection in .NET

Garbage Collection (GC) is a smart memory management system used in .NET Framework and many modern programming languages like C#. It automatically frees up memory by removing objects that your program no longer needs. You don’t have to manually delete objects—GC does this job for you! This reduces the chance of memory leaks and crashes due to out-of-memory issues.

When you create an object in C#, the CLR (Common Language Runtime) allocates memory for it in an area called the Heap. But memory is limited. As more and more objects are created, the memory gets filled up. So, to make space for new objects, the Garbage Collector comes into action. It finds and removes the objects that are no longer in use and clears their memory, so that new objects can be stored. Just like cleaning your room to make space for new things, GC cleans memory automatically in your application.

  1. Tracks Objects: GC checks which objects are still being used.
  2. Marks Unused Objects: Objects not used anymore are marked as garbage.
  3. Frees Memory: Memory occupied by unused objects is released for future use.

Heap Memory:In .NET, when you create an object using new, the CLR (Common Language Runtime) stores that object in a special memory area called the Heap. Stores reference type objects (classes). Objects stay in heap until GC removes them. Allows dynamic memory allocation at runtime.

In the .NET framework, Heap Memory is divided into 3 generations to improve the efficiency of Garbage Collection. This helps .NET manage objects with different lifetimes—some objects live only for a few seconds, while others stay in memory for the full application life.

The Common Language Runtime (CLR) automatically decides how much memory to give to each generation depending on the application needs.

Key Points:

  • Heap is used for storing reference type objects (like classes).
  • Objects in the heap are not removed automatically unless the Garbage Collector (GC) removes them.
  • It allows dynamic memory allocation, meaning memory is given at runtime.

Why Generations?

  • Most objects created in an application are short-lived (used and discarded quickly).
  • Some objects live longer (like configurations or cached data).
  • Dividing the heap into generations allows faster cleanup of short-lived objects without disturbing long-lived ones.

Phases of GC:

  1. Marking – Identify live objects
  2. Relocating – Update references for moved objects
  3. Compacting – Free memory from dead objects

To make garbage collection faster and more efficient, the .NET Heap is divided into three generations:

Generation 0 (Gen 0) – Short-Lived Objects

  • Stores newly created objects.
  • It is collected frequently, as most objects are temporary (e.g., loop variables).(These are usually temporary variables, method-level objects, etc)
  • Gen 0 is collected most frequently, and collection here is very fast.
  • If an object survives GC in Gen 0, it is promoted to Gen 1.

Example: A temporary list used inside a method. Loop variables or temporary string objects.

Generation 1 (Gen 1) – Medium-Lived Objects

  • Objects that survive Gen 0 (still being used) are moved to Gen 1. Acts as a bridge between Gen 0 and Gen 2.
  • Holds objects that survived Gen 0 GC.
  • These are not temporary, but not long-term either.
  • Acts as a buffer zone between short-term and long-term memory.
  • Collected less often than Gen 0.
  • If an object in Gen 1 still survives GC, it is promoted to Gen 2.

Example: An object used throughout a single operation or request. Objects used during an entire transaction or user request.

Generation 2 (Gen 2) – Long-Lived Objects

  • Objects that survive multiple garbage collections are moved here
  • These are long-lived objects,like static data, global caches, etc.
  • Collection is slow and expensive, so GC avoids collecting Gen 2 unless really needed.

Example: Static data, cached objects, or global settings used throughout the app.

Important Notes:

Gen 2 collection is a full GC, meaning it also collects Gen 1 and Gen 0.

Memory size:

➤ Gen 2 > Gen 1 > Gen 0(More memory is given to older generations)

The .NET GC engine automatically promotes objects from one generation to the next based on their lifespan and usage.

  • Improves Performance: GC doesn’t scan the entire heap every time.
  • Reduces Pause Time: GC first checks Gen 0 (small and fast), not whole memory.
  • Optimizes Memory Usage: Only necessary objects are scanned.

Imagine a dustbin with 3 sections:

  • Gen 0 – Daily trash (removed quickly every day).
  • Gen 1 – Items you might reuse for a few days.
  • Gen 2 – Items you store for a long time (books, files).

The cleaner (Garbage Collector) checks Gen 0 first every day, Gen 1 weekly, and Gen 2 only occasionally.

Phases of Garbage Collection

Garbage Collection follows three main phases:
  • Marking: Identifies which objects are still in use (live).
  • Relocating: Updates references to live objects that will be moved.
  • Compacting: Frees up memory by removing unreachable (dead) objects.

The Garbage Collector (GC) is a powerful part of the .NET Framework that handles memory automatically. It brings several smart features that make memory management easy, safe, and efficient.

Automatic Memory Management

  • The GC automatically takes care of memory allocation and cleanup.
  • You don’t need to manually delete objects—GC does it for you.
  • This reduces the chances of memory leaks, crashes, or other memory-related problems.

Makes life easy for developers and keeps the app stable.

Low Impact on Application Performance

  • The garbage collector usually runs in the background, so your app runs smoothly.
  • Sometimes, when a large cleanup is needed, it may pause the app for a short time.
  • These pauses are optimized to be as short as possible.

GC is designed to have minimal effect on performance.

Generation-Based Collection

  • The heap is divided into three generations: Gen 0, Gen 1, and Gen 2.
  • New objects are placed in Generation 0 (young).
  • If an object survives multiple collections, it is moved to older generations (Gen 1, Gen 2).
  • This method speeds up garbage collection because most objects are short-lived.

This generation-based approach improves speed and reduces memory pressure.

Finalization Support

  • GC supports a process called Finalization.
  • Some objects may need to perform cleanup work (like closing files or connections) before they are destroyed.
  • These objects are placed in a Finalization Queue, and GC calls their Finalize() method before deleting them.

Finalization helps in safe resource cleanup before object destruction.

In .NET, the GC class (part of the System namespace) provides methods to interact with the Garbage Collector. It allows you to check memory usage, force collections, and manage finalization.

Primary Capabilities:

  • Force garbage collection
  • Get memory usage details
  • Suppress or request finalization
  • Temporarily disable GC for high-performance code

Commonly Used Methods of GC Class:

  • GC.Collect()
    • Forces the garbage collector to run and collect all unused objects.
    • Optional overload: GC.Collect(int generation) collects up to a specified generation.
  • GC.GetTotalMemory(bool forceFullCollection)
    • Returns the estimated bytes currently allocated in managed memory.
    • If forceFullCollection is true, performs a full GC before calculating.
  • GC.MaxGeneration – Returns the maximum number of generations supported (usually 2).
  • GC.GetGeneration(object obj) – Returns the generation number (0, 1, or 2) of a specific object.
  • GC.SuppressFinalize(object obj) – Prevents the GC from calling the object's Finalize() method.
  • GC.ReRegisterForFinalize(object obj) – Re-registers an object for finalization after being suppressed.
  • GC.WaitForPendingFinalizers() – Blocks the current thread until all finalizers have run, usually used after GC.Collect().
  • GC.TryStartNoGCRegion(long totalSize) – Temporarily disables GC for high-performance code sections.
    Remember to call GC.EndNoGCRegion() after your critical code.

Example Usage:

// Force full GC and check memory usage
GC.Collect();
long memoryUsed = GC.GetTotalMemory(false);
Console.WriteLine("Memory Used: " + memoryUsed);

// Temporarily disable GC
if (GC.TryStartNoGCRegion(1024 * 1024))
{
    // Critical high-performance code here
    GC.EndNoGCRegion();
}
            

Tips: Use GC.Collect() sparingly; let .NET manage memory automatically unless in low-memory or special scenarios.

👉 Garbage Collection ensures memory efficiency, faster performance, and safer resource management in .NET.