GC basics
Learn how the garbage collector (GC) works and its generations.
What is the garbage collector?
The GC (garbage collector) is the runtime component that manages memory automatically in .NET. It groups objects by lifetime into three generations: Gen 0, Gen 1 and Gen 2.
New objects start in Gen 0. If they survive a collection they are promoted to the next generation. Gen 2 objects live long and are collected rarely; this lets short-lived objects be reclaimed quickly.
Collection and promotion
When triggered, the GC first collects Gen 0. Objects that survive Gen 0 are promoted to Gen 1. If memory is still tight, Gen 1 and Gen 2 are collected too.
This is called an ephemeral collection; it is cheap because most objects die young. Avoiding long-lived objects reduces GC pressure.
Exercise Print the generation
Create an object o = new object();. Get its generation with int gen = GC.GetGeneration(o);. Print it with Console.WriteLine($"Generation: {gen}");.
Show example solution
{gen}");
Example solution:
using System;
class Program
{
static void Main()
{
object o = new object();
int gen = GC.GetGeneration(o);
Console.WriteLine($"Generation: {gen}");
}
}
Test yourself
-
In which generation does a newly created object start?
- Gen 2
- Gen 0
- Gen 1
- Gen 3
Show answer
Gen 0 — Correct. All new objects start in Gen 0 and get promoted if they survive.
-
Get the generation info
int gen = GC.____(o);Show answer
int gen = GC.GetGeneration(o); -
What happens if an object survives a Gen 0 collection?
- It is deleted
- It is removed from memory
- It is promoted to Gen 1
- Nothing
Show answer
It is promoted to Gen 1 — Correct. Surviving objects are promoted to the next generation.