Possible Duplicate:
Resurrection difference in using Object Initializer
I am having a hard time trying to understand how garbage collector works in C# (I'm using 2012, so c# 4.5). Here is my example code:
public class A
{
public int c;
public A(){}
public A(int pC)
{
c = pC;
}
}
public static void Main()
{
// Test 1
var a = new A {c=199};
var aRef = new WeakReference(a);
a = null;
Console.WriteLine(aRef.IsAlive);
GC.Collect();
Console.WriteLine(aRef.IsAlive);
// Console.WriteLine(GC.GetGeneration(aRef.Target)); //output 1
// Test 2
a = new A (200);
aRef = new WeakReference(a);
a = null;
Console.WriteLine(aRef.IsAlive);
GC.Collect();
Console.WriteLine(aRef.IsAlive);
}
Output is True / True / True / False
It seems to me in both tests, the object on the heap has no root before calling GC.Collect. But it happens that in Test 1, the object get through the force gc run, while in Test 2 it doesn't. So, is there something mysterious going on about using initializer? My guess is that there might be "some extra code" when use initializer that would become a strong root for the same object.....
Thanks.