Slicker call to Dispose method

Posted by Miha Markič on April 15, 2009 · 1 min read

Do you ever get tired of code like this:

if (someObject != null)
{
someObject.Dispose();
}
or its shorter version
if (someObject != null)
someObject.Dispose();

Isn’t annoying to write those if (something != null) lines? Here is an extension method that does a better job:

public static class IDisposableExtensions
{
  public static void DisposeAlways(this IDisposable disposable)
{
    if (disposable != null)
disposable.Dispose();
}
}

No more ifs. Just write it like:

someObject.DisposeAlways();

DisposeAlways isn’t a perfect name though. Does anybody have a better suggestion? I can’t name it Dispose because it would conflict with existing method.