#426 – Use a Destructor to Free Unmanaged Resources
October 5, 2011 4 Comments
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.
Pingback: #646 – Value Types Don’t Have Finalizers « 2,000 Things You Should Know About C#
Pingback: #737 – When to Implement a Finalizer « 2,000 Things You Should Know About C#
Pingback: #832 – The Sequence in Which Finalizers Are Called | 2,000 Things You Should Know About C#
Pingback: #940 – Finalizers Are Called when an Application Shuts Down | 2,000 Things You Should Know About C#