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).
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With