C#C
C#4y ago
kocha

✅ I don't understand GC

The output of this code is True, False. Why? Both instances of Class1 don't have any reference pointing to them. But only one of them is garbage collected. What am I missing?

var we = Method1();
Console.WriteLine(IsGcCollected(we));

Method2();

[MethodImpl(MethodImplOptions.NoInlining)]
WeakReference Method1()
{
    var c = new Class1(1);
    return new WeakReference(c);
}

[MethodImpl(MethodImplOptions.NoInlining)]
void Method2()
{
    var c = new Class1(1);
    var w = new WeakReference(c);
    c = null;
    Console.Write(IsGcCollected(w));
}

bool IsGcCollected(WeakReference w)
{
    for (var i = 0; w.IsAlive && i < 10; i++)
    {
        GC.Collect();
        GC.WaitForPendingFinalizers();
    }

    return !w.IsAlive;
}

class Class1{
    public Class1(int propterty1)
    {
        Propterty1 = propterty1;
    }
    
    public int Propterty1 { get; set; }
}
Was this page helpful?