A simple, educational garbage collector written in C# for .NET. Perfect for students learning how garbage collection works!
Garbage Collection (GC) is automatic memory management. When you create objects in code, they're stored in memory. When you're done with them, the GC automatically frees that memory so other programs can use it.
dotnet runOur GC uses Mark-Sweep algorithm with 3 phases:
- Start from "roots" (variables in your code)
- Mark every object we can reach as alive
- Walk through all objects in the heap
- If object is NOT marked → it's garbage! Free it.
- If object IS marked → keep it
- Move objects together to reduce gaps (simplified in this version)
| File | Purpose |
|---|---|
GCObject.cs |
Base class for all GC objects |
Heap.cs |
Memory manager |
GC.cs |
Main GC with Mark/Sweep |
GcRootHandle.cs |
Keeps objects alive |
MyData.cs |
Example test class |
Program.cs |
Demo program |
// Allocate an object
var obj = GC.Instance.New<MyData>();
obj.Value = 42;
obj.Name = "Test";
// Run garbage collection
GC.Instance.Collect();
// Print statistics
GC.Instance.PrintStats();- Bump Pointer Allocation - Fast memory allocation (just increment an index)
- Free List - Track freed memory for reuse
- Mark-Sweep - Foundation of GC algorithms
- Root Handles - References that keep objects alive
- Object Headers - Metadata about each object
- Add reference tracing - follow references within objects
- Implement compaction - move objects together
- Add generational GC - young/old generations
- Use Marshal.AllocHGlobal - real OS memory
GNU General Public License v3.0 - See LICENSE file
Happy Learning! 🚀