Garbage Collection in C# | .NET Framework (original) (raw)

Garbage Collection is the process of automatically freeing memory by removing objects that are no longer accessible by any part of the program. This ensures that unused objects do not consume memory indefinitely.

If no variable holds a reference to an object, that object becomes eligible for garbage collection.

**Note:

Garbage Collector (GC), a component of the Common Language Runtime (CLR) automatically reclaims memory occupied by objects that are no longer in use, so developers don’t need to manually free memory as in languages like C or C++

Features of Garbage Collection

Generations in Garbage Collection

To improve performance, the Garbage Collector (GC) organizes objects in the heap into generations. This strategy is based on the observation that most objects are short-lived, while a smaller portion live longer.

heap_generation_in_garbage_collection

Generation in Garbage Collection

Generation 0 (Newly Allocated Objects)

Generation 1 (Survivors of Gen 0 Collection)

Generation 2 (Long-Lived Objects)

**Example: Count of the number of Generations.

C# `

// Using MaxGeneration property of GC class to get the number of generations using System;

public class Geeks { public static void Main(string[] args) { Console.WriteLine("The number of generations are: " + GC.MaxGeneration); } }

`

Phases in Garbage Collection

Garbage collection runs in phases to clean memory in an organized and efficient way. These phases ensure that unused memory is reclaimed, references are updated and fragmentation is reduced.

phase_in_garbage_collection

Phases in Garbage Collection

1. Marking Phase

2. Relocating Phase (sometimes included within Mark & Compact)

3. Compacting Phase

Important Garbage Collection Methods

The System.GC class provides methods to interact with the garbage collector.

1. GC.Collect()

Forces garbage collection of all generations.

C# `

using System;

class Program { static void Main() { for (int i = 0; i < 1000; i++) { var obj = new object(); }

    GC.Collect(); // Forces garbage collection
    GC.WaitForPendingFinalizers();

    Console.WriteLine("Forced garbage collection completed.");
}

}

`

**Note: Not recommended in normal scenarios, as it can affect performance.

2. GC.GetTotalMemory()

Returns the number of bytes currently allocated in managed memory.

C++ `

using System;

class Program { static void Main() { long before = GC.GetTotalMemory(false); int[] arr = new int[1000]; long after = GC.GetTotalMemory(false);

    Console.WriteLine($"Memory before: {before}");
    Console.WriteLine($"Memory after: {after}");
}

}

`

3. GC.MaxGeneration

Returns the maximum generation supported by the system (usually 2).

C# `

Console.WriteLine("Maximum Generation: " + GC.MaxGeneration);

`

4. GC.GetGeneration(object obj)

Returns the generation in which a given object resides.

C# `

string name = "Hello"; Console.WriteLine("Generation of name: " + GC.GetGeneration(name));

`

5. GC.WaitForPendingFinalizers()

C# `

GC.Collect(); GC.WaitForPendingFinalizers();

`

Advantages of Garbage Collection

Limitations of Garbage Collection