static destructor

C#.Net

C# Problem Overview


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

I am wondering if there is static destructor?

C# Solutions


Solution 1 - C#

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

Solution 2 - C#

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

Solution 3 - C#

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.

Solution 4 - C#

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.

Solution 5 - C#

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)

Solution 6 - C#

No there is nothing like destructor for static classes but you can use Appdomain.Unloaded event if you really need to do something

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser496949View Question on Stackoverflow
Solution 1 - C#zackery.fixView Answer on Stackoverflow
Solution 2 - C#Tod ThomsonView Answer on Stackoverflow
Solution 3 - C#mmxView Answer on Stackoverflow
Solution 4 - C#Neil KnightView Answer on Stackoverflow
Solution 5 - C#Dean ChalkView Answer on Stackoverflow
Solution 6 - C#TalentTunerView Answer on Stackoverflow