O'Reilly logo

C# in a Nutshell by Peter Drayton, Ted Neward, Ben Albahari

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Dispose and Close Methods

Implementing a finalizer gives your type an opportunity to release any external unmanaged resources (such as database connections or file handles) that it may be holding onto. From the perspective of the users of your type, this makes the resource management implicit: they interact with your type, and your type interacts with the resource as needed. However, since GC happens asynchronously and there are no guarantees as to exactly when the finalizers will be called, this level of control may not be sufficient. In these cases, it is good practice to also offer clients explicit resource management controls.

To provide explicit resource management to clients of your type, implement the IDisposable interface. This offers clients a Dispose() method they can call to explicitly instruct you to release resources. For types in which Dispose() doesn’t make sense, provide an explicit Close() method that optionally forwards to a private implementation of IDisposable.Dispose. If your type also has a finalizer (via a C# destructor), your Dispose() or Close() implementation should include a special call to the static SuppressFinalize() method on the System.GC type to indicate that the destructor no longer needs to be called. Typically, the real finalizer is written to call the Dispose/Close method, as follows:

using System; public class Worker : IDisposable { int id; public Worker(int id) { this.id = id; } // ... protected virtual void Dispose(bool disposing) { if (disposing) ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required