C# (and .NET in general) offers static constructors for classes, but why are there no static destructors? I needed such a static destructor for a class that had to clean up resources. So I created a little helper-class that adds static destructor-functionality to a class:
public delegate void DestructorDelegate();
public sealed class Destructor
{
private readonly DestructorDelegate _destructorMethod;
public Destructor(DestructorDelegate method)
{
_destructorMethod = method;
}
~Destructor()
{
if (_destructorMethod != null)
{
_destructorMethod();
}
}
}
Here’s an example that shows how to use it:
public class MyClass
{
private static readonly Destructor _destructor;
static MyClass()
{
DestructorDelegate destructorMethod;
destructorMethod = new DestructorDelegate(Destroy);
_destructor = new Destructor(destructorMethod);
}
private static void Destroy()
{
// this is the static destructor-method
}
}