How Garbage Collector Works in C#: Explained Simply
The
Garbage Collector in C# automatically frees memory used by objects that are no longer referenced in the program. It runs in the background, tracking object usage and cleaning up to prevent memory leaks without manual intervention.Syntax
The garbage collector in C# is part of the System.GC class. You can interact with it using methods like GC.Collect() to force a collection, but normally it runs automatically.
GC.Collect(): Forces garbage collection immediately.GC.GetTotalMemory(bool): Returns the amount of memory currently allocated.GC.SuppressFinalize(object): Prevents finalization of an object.
csharp
using System; class Program { static void Main() { // Force garbage collection GC.Collect(); // Get total memory used long memory = GC.GetTotalMemory(false); Console.WriteLine($"Memory used: {memory} bytes"); } }
Output
Memory used: 123456 bytes
Example
This example shows how objects are created and then become eligible for garbage collection when no longer referenced. The garbage collector frees their memory automatically.
csharp
using System; class MyClass { public int Id; public MyClass(int id) { Id = id; } ~MyClass() { Console.WriteLine($"Finalizing object {Id}"); } } class Program { static void Main() { CreateObjects(); // Force garbage collection to see finalizers run GC.Collect(); GC.WaitForPendingFinalizers(); Console.WriteLine("Garbage collection complete."); } static void CreateObjects() { MyClass a = new MyClass(1); MyClass b = new MyClass(2); a = null; // 'a' object is now unreferenced b = null; // 'b' object is now unreferenced } }
Output
Finalizing object 1
Finalizing object 2
Garbage collection complete.
Common Pitfalls
Developers often misunderstand how and when garbage collection happens. Forcing GC.Collect() too often can hurt performance. Also, objects with unmanaged resources need explicit cleanup using IDisposable and Dispose() to avoid resource leaks.
Another mistake is holding references unintentionally, which prevents objects from being collected.
csharp
using System; class ResourceHolder : IDisposable { private bool disposed = false; public void Dispose() { if (!disposed) { Console.WriteLine("Cleaning up unmanaged resources."); disposed = true; GC.SuppressFinalize(this); } } ~ResourceHolder() { Dispose(); } } class Program { static void Main() { using (var holder = new ResourceHolder()) { // Use resource } // Dispose called automatically here } }
Output
Cleaning up unmanaged resources.
Quick Reference
Garbage Collector Tips:
- It runs automatically; manual calls are rarely needed.
- Use
IDisposableandDispose()for unmanaged resources. - Nullify references to help GC identify unused objects.
- Finalizers (~ClassName) run before memory is freed but can delay collection.
- Excessive forced collections hurt performance.
Key Takeaways
C# garbage collector automatically frees memory of objects no longer in use.
Avoid forcing garbage collection manually to keep performance smooth.
Use IDisposable and Dispose for cleaning unmanaged resources properly.
Unintentional references prevent objects from being collected.
Finalizers run before memory is freed but should be used carefully.