I was testing a class that uses weak references to ensure that objects were able to be garbage collected and I found that objects in a List<> were never collected even if the list is no longer referenced. This is also the case with a simple array. The following code snippet shows a simple test that fails.
class TestDestructor
{
public static bool DestructorCalled;
~TestDestructor()
{
DestructorCalled = true;
}
}
[Test]
public void TestGarbageCollection()
{
TestDestructor testDestructor = new TestDestructor();
var array = new object[] { testDestructor };
array = null;
testDestructor = null;
GC.Collect();
GC.WaitForPendingFinalizers();
Assert.IsTrue(TestDestructor.DestructorCalled);
}
Leaving out the initialisation of the array causes the test to pass.
Why is the object in the array not getting garbage collected?
Another edit: result will be always false if the array is defined in the Main()-Method-Scope, but will be true if defined in the Class-Test-Scope. Maybe thats not a bad thing.