Brian Hartsock's Blog

C# Destructors and IDisposable

by bhartsock on Jun.19, 2008, under .NET, Programming

This week I found myself somewhat confused on when to use destructor. Originally I assumed that anytime you implement IDisposable you should have a destructor that calls Dispose().

This is not the case though. The only time you really need a destructor is when a class directly contains unmanaged resources, like file handles.

A good example of when not to use a destructor is a wrapper class. For instance, if you have a database connection class wrapped with some sort of adapter class, the adapter class doesn’t need a destructor. It still needs to implement IDisposable to enable early disposal of resources, but the destructor of the underlying database connection class will handle any potential leak cases if Dispose() isn’t called.

Here is a quote from a very good article on C# traps:

The destructor should only release unmanaged resources that your object holds on to, and it should not reference other objects. If you have only managed references you do not need to (and should not) implement a destructor. You want this only for handling unmanaged resources. Because there is some cost to having a destructor, you ought to implement this only on methods that consume valuable, unmanaged resources.

The really powerful statement is “it should not reference other objects” which basically backs up my previous statement on wrapper classes.

Here is another good article on destructors and IDisposable.

Post to Twitter Post to Digg Post to Facebook Post to Reddit

:,

Leave a Reply

Post by day

June 2008
M T W T F S S
« May   Jul »
 1
2345678
9101112131415
16171819202122
23242526272829
30