There are two scenario that i trying to understand how will GC will act
1- There is two object – object1 and object2
object1 has reference on object2 and object2 has reference on object1
Now, both of those object are not in use and GC can collect them.
What will happened ? does GC skip on this collection ? ?
2- Same question but we have 4 ( or n ) objects that have reference on each other.
What GC will do on this case ???
The GC used by .NET is a tracing garbage collector (“Mark and Sweep” is a related term)
Memory objects are considered “garbage” if they can no longer be reached by following pointers/references from the non-garbage part of your program’s memory.
To determine what is reachable and what is not, the GC first establishes a set of root references/pointers. Those are references that are guaranteed to be reachable. Examples include local variables and static fields.
It then follows these references recursively (traces) and marks each object it encounters as “not garbage”. Once it runs out of references to follow, it enters the “sweep” phase where every object that has not been marked as “non garbage” is freed (which might include invoking the object’s finalizer).
So as soon as none of the objects in your “object ring” is referenced by any part of your “live” objects, it will be garbage collected.