© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•4y ago•
4 replies
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; }
}
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; }
}
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

✅ I don't understand what I did wrong(list)
C#CC# / help
3y ago
Don’t understand nullable reference types
C#CC# / help
4y ago
I don't understand the content of the image
C#CC# / help
5w ago
I don't understand this warning: BL Mapping (Mapperly)
C#CC# / help
13mo ago