views:

139

answers:

4

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()
    {

    }
}
+8  A: 

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...

Marc Gravell
+2  A: 

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

Aaron Maenpaa
+1  A: 

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.

John Saunders
Why is dtor/finalizer different? A C# dtor is mapped to Finalize, right?
Henk Holterman
destructor and finalizer - both terms have been used interchangeably in official documentation. The word used doesn't affect the behaviour...
Marc Gravell
@Marc: I've never seen it called a destructor. Can you reply with a link that does so?
John Saunders
+2  A: 

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

Michael Burr