When Garbage Collection Is Needed?
Generation in Garbage Collection.
Most objects are short-lived. To optimize performance, objects are grouped into generations based on their longevity. Each generation is collected at different frequencies.
1. Generation 0 (Gen 0)
If an object survives a Gen 0 collection, it is promoted to Generation 1.
void CreateObjects() { int x = 10; var temp = new object(); // Gen 0 object }
- Temporary objects
- Method-local objects
- Short-lived calculations
2. Generation 1 (Gen 1)
class CacheItem { public string Data { get; set; } } CacheItem item = new CacheItem(); // Starts in Gen 0
- Objects with medium lifetime
- Temporary caches
- Objects shared across a few methods
3. Generation 2 (Gen 2)
class AppConfig { public static AppConfig Instance = new AppConfig(); }
- Static objects
- Singletons
- Long-lived caches
- Application-wide configuration data
Large Object Heap (LOH)
- LOH objects are collected only during Gen 2 GC
- Not compacted by default (to avoid performance cost)
byte[] largeArray = new byte[100_000]; // LOH
- Gen 0 collections are fast and frequent
- Gen 1 filters objects before reaching Gen 2
- Gen 2 collections are rare but thorough
- Improves overall performance and responsiveness
| Generation | Lifetime | Collection Frequency |
|---|---|---|
| Gen 0 | Short-lived | Very frequent |
| Gen 1 | Medium-lived | Less frequent |
| Gen 2 | Long-lived | Rare |
| LOH | Very large objects | During Gen 2 |
How Garbage Collection is Triggered Automatically?
- The managed heap does not have enough free space for new allocations
- Allocation pressure becomes high (too many objects being created quickly)
- A generation threshold is exceeded (Gen 0, Gen 1, or Gen 2)
- The system is under memory pressure (low available RAM)
- The application enters certain runtime phases (for example, during idle time)
- At this point, the CLR decides on its own that a garbage collection cycle is required and pauses the application briefly to perform it.
How To Manually Call Garbage Collection in C#?
using System; using System.Collections.Generic; class Program { static void Main() { Console.WriteLine("Application started"); CreateLargeObjects(); Console.WriteLine("Large objects created and released"); // Force garbage collection GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); Console.WriteLine("Garbage collection completed"); Console.ReadLine(); } static void CreateLargeObjects() { List<byte[]> largeData = new List<byte[]>(); for (int i = 0; i < 10; i++) { // Each array is ~10 MB largeData.Add(new byte[10_000_000]); } // Remove references largeData = null; Console.WriteLine("References removed"); } }
- The application allocates large objects (LOH).
- References are explicitly removed.
- GC.Collect() forces garbage collection.
- GC.WaitForPendingFinalizers() ensures finalizers run.
- Memory is reclaimed immediately.
What is the use of Dispose() method in C#?
class FileLogger : IDisposable { private StreamWriter _writer = new StreamWriter("log.txt"); public void Write(string message) { _writer.WriteLine(message); } public void Dispose() { _writer.Dispose(); // releases file handle immediately Console.WriteLine("Resources released using Dispose()"); } }
using (var logger = new FileLogger()) { logger.Write("Hello"); } // Dispose() is called automatically here
- Dispose() releases unmanaged resources immediately.
- It is called explicitly by the developer or via the using keyword.
- Provides predictable and safe cleanup.
- Preferred over Finalize() for resource management.
Dispose() is used to deterministically release unmanaged resources as soon as they are no longer needed, improving performance and reliability.
What is the use of Finalizer in C#?
class NativeResource { ~NativeResource() { // Release unmanaged resource Console.WriteLine("Finalize called"); } }
Best Practices for Garbage Collection
- Avoid unnecessary object creation
- Reuse objects when possible
- Dispose of unmanaged resources properly
- Avoid manual GC.Collect()
- Use using for streams, files, and DB connections
- Be careful with static references



