C#
C#

help

Root Question Message

kocha
kocha11/19/2022
✅ 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; }
}
 
Oryp4ik
Oryp4ik11/19/2022
🤔:thinkinggura::catthinking::csharpthink::pringlethink:
Oryp4ik
Oryp4ik11/19/2022
ok no idea, try #663803973119115264 or #312132327348240384
ContactFrequently Asked QuestionsJoin The DiscordBugs & Feature RequestsTerms & Privacy