Search code examples
c#destructoridisposableunmanagedresources

IDisposable and Destructors in abstract base class


I have an abstract base class which implements IDisposable and the full bool disposed = false, Dispose(), and Dispose(bool) pattern except for the destructor. The base class implements IDisposable since many of its derived classes need to release unmanaged resources. However, I heard that classes with destructors are expensive and thus would make the derived classes that do not have unmanaged resources unnecessarily expensive, had I included the destructor. I'm confused on this matter. Should I or should I not include the destructor and why? Thanks.


Solution

  • You only need to include a destructor/finalizer if you are implementing an entirely new kind of unmanaged resource. So if you're just wrapping or inheriting an existing database connection type, socket type, gdi resource, etc, then you do not need a destructor. The destructor in the original type will take care of finally releasing that resource for you. But if you are implementing something like the ADO.Net provider objects for an entirely new kind of database from scratch, then you would want to implement a destructor for your connection type, so that it can release it's connection when it is finally collected.