Code Reviews and IDisposable

Warning: C# biased code to follow.....

Been doing a lot of code reviews lately and one thing I have noticed is either a lack of use of the IDisposable interface or simply not knowing it even exists let alone its purpose. Just recently I reviewed some code where explicit calls to GC.Collect() have been thrown in to “help reclaim memory”. It ended up being that another component in a library they used was making unmanaged calls and the developers were not calling the Dispose() method  but it was of concern that the first port of call for this developer was to throw in this explicit call to GC.Collect(). Whats even more concerning is that the Tech lead in this project advocated this and when I mentioned the preferred use of IDisposable interface in the offending component I received a blank stare and a response of “uummmmmm....”.

While its obvious that all that is bad thing it brings up a point I have been thinking about. The IDisposable interface is, IMHO, not best way of implementing the release of unmanaged resources. It just “feels” a bit too manual. the “using” statement helps but its still manual. If a class you are using implements IDisposable, then you should call Dispose(), and along with this you generally must call GC.SuppressFinalize(this); to prevent the finalizing of the object. Ideally I'd like the framework to do all this for me. Granted, just calling the Dispose() method is not really hard, its just seems more manual than it should be, given the usual crucial nature of its operation. When you supply a Finalize() method, the framework calls that. I am sure a similar method could be employed, but I am no compiler expert.Perhaps something like:-

public class SomeClass : IDisposable
    public Dispose() { ...... }

And let the framework do the rest. All callers of this class would not worry about calling the Dispose method as it would do this for them, and suppress its finalzation as well. Then again, perhaps I am making too much of a fuss over things. I'd be interested too hear if anyone else thinks the same or simply feels I am rambling...


  • I try to avoid getting my code involved in garbage collection.

    If I use an object that needs to have .Dispose called, I would like to see a compiler warning, as my understanding implies that a GC system "takes care of it's own".

  • Thats kind of what I had in mind and sometimes, you have to use unmanaged resources, although this may be less of an issue in Whidbey/Longhorn.

Comments have been disabled for this content.