Slicker call to Dispose method

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.

10 thoughts on “Slicker call to Dispose method

  1. @Milan: That’s an interesting using’s side effect indeed. Good to know. I find my way cleaner though. Writing "using (x as IDisposable) {}" is more writting and the intention is less obvious – that’s my subjective thinking.

  2. Haha, I have to win, it is my blog :-P. Anyway, there is another advantage for you: you don’t have to include any additional namespace. That wouldn’t be a problem if VS could add extension method’s namespace automatically as it does for normal classes – Shift-Alt+F10.

Leave a Reply