Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In what situation(s) would a reference point to an object that was queued for garbage collection?

I'm reading through a C# topic on Dispose() and ~finalize and when to use which. The author argues that you should not use references within your ~finalize because it's possible the object you're referencing may already be collected. The example specifically stated is, ".. you have two objects that have references to each other. If object #1 is collected first, then object #2's reference to it is pointing to an object that's no longer there."

In what scenarios would an instance of an object be in a state where it has a reference in memory to an object that is being GC'd? My guess is there are at least two different scenarios, one where the object reference is pointing at an object and one where the object reference is pointing at another object reference (eg. when it was passed by ref in a method).

like image 437
chopperdave Avatar asked Feb 28 '12 21:02

chopperdave


1 Answers

You can have objects that reference each other, and the entire set can be eligible for GC.


Here is a simple code sample:

class Test { 
     public Test Other { get; set;} 

     static void Main()
     {
          Test one = new Test();
          Test two = new Test { Other = one; }
          one.Other = two;

          one = null;
          two = null
          // Both one and two still reference each other, but are now eligible for GC
     }
}
like image 92
Reed Copsey Avatar answered Sep 30 '22 17:09

Reed Copsey