Implementing IDisposable on a sealed class

From Joe Duffy's Weblog:

For sealed classes, this pattern need not be followed, meaning you should simply implement your Finalizer and Dispose with the simple methods (i.e. ~T() (Finalize) and Dispose() in C#). When choosing the latter route, your code should still adhere to the guidelines below regarding implementation of finalization and dispose logic.

So yes, you should be good.

You do need the finalizer as Mehrdad mentioned. If you want to avoid it, you might take a look at SafeHandle. I don't have enough experience with P/Invoke to suggest the correct usage.


The finalizer is necessary as a fallback mechanism to eventually free unmanaged resources if you forgot to call Dispose.

No, you shouldn't declare a virtual method in a sealed class. It wouldn't compile at all. Also, it's not recommended to declare new protected members in sealed classes.


A minor addition; in the general case, a common pattern is to have a Dispose(bool disposing) method, so that you know whether you are in Dispose (where more things are available) vs the finalizer (where you shouldn't really touch any other connected managed objects).

For example:

 public void Dispose() { Dispose(true); }
 ~MemBlock() { Dispose(false); }
 void Dispose(bool disposing) { // would be protected virtual if not sealed 
     if(disposing) { // only run this logic when Dispose is called
         GC.SuppressFinalize(this);
         // and anything else that touches managed objects
     }
     if (ptr != IntPtr.Zero) {
          Marshal.FreeHGlobal(ptr);
          ptr = IntPtr.Zero;
     }
 }

Tags:

C#

Pinvoke