How does garbage collection and scoping work in C#? [duplicate]

The dotnet GC engine is a mark-and-sweep engine rather than a reference-counter engine like you’re used to in python. The system doesn’t maintain a count of references to a variable, but rather runs a “collection” when it needs to reclaim RAM, marking all of the currently-reachable pointers, and removing all the pointers that aren’t reachable (and therefore are out of scope).

You can find out more about how it works here:
http://msdn.microsoft.com/en-us/library/ee787088.aspx

The system finds “reachable” objects by starting at specific “root” locations, like global objects and objects on the stack, and traces all objects referenced by those, and all the objects referenced by those, etc., until it’s built a complete tree. This is faster than it sounds.

Leave a Comment