Last Updated: February 25, 2016
·
460
· kryil

Abuse IDisposable in C#

Say you have to create a temporary directory and delete it after you're done.
So you write code like this:

DirectoryInfo tmpdir = Helper.CreateTemporaryDirectory();

DoStuff(tmpdir);

tmpdir.Delete(true);

Easy, right? Well, what if there's an exception and the directory is newer
deleted? You can, of course, wrap the calls to try-finally, but it can be
very cumbersome, especially if you need to do it a lot.

To remedy this you can implement IDisposable and let the compiler worry
about everything:

class TemporaryDirectory : IDisposable
{
    public DirectoryInfo Directory { get; private set; }

    public TemporaryDirectory()
    {
        Directory = Helper.CreateTemporaryDirectory();
    }

    public void Dispose()
    {
        if (Directory != null)
            Directory.Delete(true);
        Directory = null;
    }
}

When you use your new class like this:

using (var tmpdir = new TemporaryDirectory())
    DoStuff(tmpdir.Directory);

You don't have to worry about cleaning up as it will happen automatically.