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.
Written by Ilari Mäkimattila
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Idisposable
Authors
markm
10.14K
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#