Question

Please see code below. The destructors are never called. Anyone know why and how this can be rectified?

public partial class Form1 : Form
{
    private Goo goo;

    public Form1()
    {
        InitializeComponent();

        goo = Goo.GetInstance();         
    }
}

public class Goo
{
    private foo f = new foo();
    private static Goo goo;
    private Goo()
    {}

    public static Goo GetInstance()
    {
        if(goo!=null)
        {
            goo = new Goo();
        }
        return goo;
    }

    ~Goo()
    {

    }
}

class foo
{
    ~foo()
    {

    }
}
Was it helpful?

Solution

Objects referenced by static fields are not simply finalized unless you clear (set to null) the field - and even then it is non-deterministic and not guaranteed. Static fields count as root objects.

When (and why) would you expect this to be collected/finalized? It is still accessible...

OTHER TIPS

Objects referenced by static fields are always reachable (assuming no class unloading or any other GC funkiness) and will never be collected.

Even though you might expect the finalizer on static objects to run when the process is shutdown, there are no guarantees there either:

That's not a destructor. It's a finalizer. That's a different thing. As the other two have said, because this is a static, it will never be collected, hence the finalizer will never run.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top