What is garbage collection in C#?

The garbage collector (GC) in C# is an automatic memory management system that handles the allocation and release of memory for managed objects. It eliminates the need for manual memory management, preventing memory leaks and reducing programming errors.

The garbage collector operates on the managed heap, where all reference type objects are stored. When objects are no longer referenced by the application, the GC automatically reclaims their memory space.

How Garbage Collection Works

Garbage Collection Process Object Created Memory Low GC Triggered Memory Free new keyword Heap full Mark & Sweep Available space Three Phases of GC 1. Mark (identify unreachable objects) 2. Sweep (remove objects) 3. Compact (defragment heap)

Example of Object Lifecycle

using System;

class Person {
   public string Name { get; set; }
   public Person(string name) {
      Name = name;
      Console.WriteLine($"Person {Name} created");
   }
   
   ~Person() {
      Console.WriteLine($"Person {Name} finalized");
   }
}

class Program {
   public static void Main() {
      CreateObjects();
      
      Console.WriteLine("Forcing garbage collection...");
      GC.Collect();
      GC.WaitForPendingFinalizers();
      
      Console.WriteLine("Program ending...");
   }
   
   static void CreateObjects() {
      Person p1 = new Person("Alice");
      Person p2 = new Person("Bob");
      
      Console.WriteLine("Objects created, leaving scope...");
   }
}

The output of the above code is −

Person Alice created
Person Bob created
Objects created, leaving scope...
Forcing garbage collection...
Person Bob finalized
Person Alice finalized
Program ending...

Advantages of Garbage Collection

  • Automatic Memory Management − You don't need to manually free memory, preventing memory leaks.

  • Efficient Allocation − Objects are allocated on the managed heap efficiently using a simple pointer increment.

  • Memory Reclamation − Unused objects are automatically identified and their memory is reclaimed for future allocations.

  • Clean Object Initialization − Managed objects start with clean memory content, so constructors don't need to initialize every field to zero.

  • Heap Compaction − The GC compacts memory to reduce fragmentation and improve allocation performance.

Generations in Garbage Collection

The .NET garbage collector uses a generational approach to optimize performance −

Generation Description Collection Frequency
Generation 0 Newly created objects Most frequent
Generation 1 Objects that survived one GC cycle Less frequent
Generation 2 Long-lived objects Least frequent

Example of GC Information

using System;

class GCDemo {
   public static void Main() {
      Console.WriteLine("Initial memory usage:");
      ShowGCInfo();
      
      // Create many objects
      for (int i = 0; i < 10000; i++) {
         string temp = "Object " + i;
      }
      
      Console.WriteLine("\nAfter creating objects:");
      ShowGCInfo();
      
      GC.Collect();
      Console.WriteLine("\nAfter garbage collection:");
      ShowGCInfo();
   }
   
   static void ShowGCInfo() {
      Console.WriteLine($"Gen 0 collections: {GC.CollectionCount(0)}");
      Console.WriteLine($"Gen 1 collections: {GC.CollectionCount(1)}");
      Console.WriteLine($"Gen 2 collections: {GC.CollectionCount(2)}");
      Console.WriteLine($"Total memory: {GC.GetTotalMemory(false)} bytes");
   }
}

The output of the above code is −

Initial memory usage:
Gen 0 collections: 0
Gen 1 collections: 0
Gen 2 collections: 0
Total memory: 32768 bytes

After creating objects:
Gen 0 collections: 1
Gen 1 collections: 0
Gen 2 collections: 0
Total memory: 57344 bytes

After garbage collection:
Gen 0 collections: 2
Gen 1 collections: 0
Gen 2 collections: 0
Total memory: 32768 bytes

Conclusion

Garbage collection in C# provides automatic memory management through a sophisticated system that tracks object references and reclaims unused memory. This generational approach optimizes performance by collecting short-lived objects more frequently than long-lived ones, making C# applications both memory-efficient and developer-friendly.

Updated on: 2026-03-17T07:04:35+05:30

9K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements