static destructor

C# has static constructor which do some initialization (likely do some unmanaged resource initialization).

I am wondering if there is static destructor?


Not exactly a destructor, but here is how you would do it:

class StaticClass 
{
   static StaticClass() {
       AppDomain.CurrentDomain.ProcessExit +=
           StaticClass_Dtor;
   }

   static void StaticClass_Dtor(object sender, EventArgs e) {
        // clean it up
   }
}

This is the best way (ref: https://stackoverflow.com/a/256278/372666)

public static class Foo
{
    private static readonly Destructor Finalise = new Destructor();

    static Foo()
    {
        // One time only constructor.
    }

    private sealed class Destructor
    {
        ~Destructor()
        {
            // One time only destructor.
        }
    }
}

No, there isn't.

A static destructor supposedly would run at the end of execution of a process. When a process dies, all memory/handles associated with it will get released by the operating system.

If your program should do a specific action at the end of execution (like a transactional database engine, flushing its cache), it's going to be far more difficult to correctly handle than just a piece of code that runs at the end of normal execution of the process. You have to manually handle crashes and unexpected termination of the process and try recovering at next run anyway. The "static destructor" concept wouldn't help that much.


No, there isn't. The closest thing you can do is set an event handler to the DomainUnload event on the AppDomain and perform your cleanup there.


Initializing and cleaning up unmanaged resources from a Static implementation is quite problematic and prone to issues.

Why not use a singleton, and implement a Finalizer for the instance (an ideally inherit from SafeHandle)