Rant of the day: IDisposable

My colleagues are probably used to the fact that I rant about code quality frequently. I take code quality very seriously. Not because I’m especially expert in it, but because features of basic code quality make it easier for other people to read and maintain the code.

Today’s irritation comes from some code (replicated in a number of classes I might add) that implements IDisposable. It is a fine interface and by implementing it you are telling the rest of the world that you have some stuff that can’t just be left to the garbage collector to clean up. These are things like file streams, database connections, etc. Any type of scarce resource that you want to hand back as soon as you are finished with it rather than leave it up to the garbage collector.

However, I came across this “gem” in some code today where the class, basically a utility class, contained no fields (so it wasn’t holding on to anything at all, let alone anything that might be a scarce resource). Yet, for some reason it implemented IDisposable. What was it going to dispose? What could it dispose?

The answer was in the code:

public void Dispose()
    // Nothing to dispose of.



  1. Liam Westley says:

    You need to implement IDisposable If you like to use the C# syntax for using. using (SomeObject obj = new SomeObject()) { // do stuff }The actual implementation might not do any releasing of objects, but it can create readable code which is future proof for the moment when you do actually need to implement a Dispose method.

  2. Well, I could see that. However, I’d only do that if I could see the class was likely to need to be disposable at some point in the future. In other words, there would be a plan to add in stuff that needed to be disposed of.

  3. Navaneeth says:

    A utility class which has no state to maintain should be static, right? So compiler will alert when IDisposable is implemented.

  4. Colin Mackay says:

    @Navaneeth Indeed. No state in the class makes it a good candidate for being a static class. But in this instance it wasn’t a even a static class.

Leave a Reply to Navaneeth Cancel reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s