Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't static classes have destructors?

Two parts to this:

  1. If a static class can have a static constructor, why can't it have a static destructor?

  2. What is the best workaround? I have a static class that manages a pool of connections that are COM objects, and I need to make sure their connections get closed/released if something blows up elsewhere in the program.

like image 992
Jon Seigel Avatar asked Nov 26 '09 19:11

Jon Seigel


1 Answers

Instead of a static class, you should use a normal class with the singleton pattern (that is, you keep one single instance of the class, perhaps referenced by one static property on the class itself). Then you can have a destructor, or even better, a combination of destructor and Dispose method.

For example, if you now have:

static class MyClass
{
    public static void MyMethod() {...}
}

//Using the class:
MyClass.MyMethod();

you would have instead:

class MyClass : IDisposable
{
    public static MyClass()
    {
        Instance=new MyClass();
    }

    public static MyClass Instance {get; private set;}

    public void MyMethod() {...}

    public void Dispose()
    {
        //...
    }

    ~MyClass()
    {
        //Your destructor goes here
    }
}

//Using the class:
MyClass.Instance.MyMethod();

(Notice how the instance is created in the static constructor, which is invoked the first time that any of the class static members is referenced)

like image 150
Konamiman Avatar answered Sep 26 '22 16:09

Konamiman