#426 – Use a Destructor to Free Unmanaged Resources

When an object is no longer referenced by other objects, its memory may be reclaimed by the garbage collector in the CLR.  If you have any unmanaged resources that you need to clean up explicitly, you can implement a finalizer for your class.

A finalizer is the implementation of the Object.Finalize method for your class, which the garbage collector calls when it’s ready to release memory for an object.  In C#, you implement a finalizer using the destructor syntax–a method defined as a tilde (~), followed by the name of the class.

    public class Dog
    {
        ~Dog()
        {
            Trace.WriteLine("This dog is on the way out..");
        }

When you look at the IL for this class, you’ll see that the compiler has overridden the Finalize method.

You’ll notice that this method is now called when the garbage collector is releasing the object.

Advertisements