C# Garbage Collector Ressurection NullRefException
c#, garbage-collection
Solution
You need a call to GC.WaitForPendingFinalizers. Without this, your destructor won't actually get called in order.
static void Main()
{
// Create A instance and print its value
A a = new A(50);
a.Print();
// Strand the A object (have nothing point to it)
a = null;
// Activate the garbage collector
GC.Collect();
// Add this to wait for the destructor to finish
GC.WaitForPendingFinalizers();
// Print A's value again
B.IntA.Print();
}
Problem
I have this code (taken for a very good and friendly web site) ``` public class B { static public A IntA; } public class A { private int x; public A(int num) { x = num; } public void Print() { Console.WriteLine("Value : {0}", x); } ~A() { B.IntA = this; } } class RessurectionExample { // Ressurection static void Main() { // Create A instance and print its value A a = new A(50); a.Print(); // Strand the A object (have nothing point to it) a = null; // Activate the garbage collector GC.Collect(); // Print A's value again B.IntA.Print(); } } ``` It creates an instance of A with the value 50, prints it, strands the created object by setting his only reference to null, activates his Dtor and after being saved at B - prints it again. Now, the weird thing is that when debugging, when the cursor points to the last line (B.IntA.Print()), the value of the static A member is null, after pressing F10, I get a NullReferenceException BUT the value of the static A member changes to what it should be. Can anyone explain this phenomenon?