Slicker call to Dispose method

Do you ever get tired of code like this:

if (someObject != null)
or its shorter version
if (someObject != null)

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)
No more ifs. Just write it like:

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.

Comments (10) -

  • Miki Watts

    4/16/2009 1:31:46 AM | Reply

    how about SafeDispose? I usually add the prefix Safe when I create functions that are designed to handle cases like this.

  • Matija Lah

    4/16/2009 8:31:06 PM | Reply

    The way they usually do it at MS the only option is Dispose2.

  • Miha

    4/18/2009 2:52:59 AM | Reply


    SafeDispose -- there's nothing safe about it, really. Smile

  • Miha Markic

    5/3/2009 4:02:47 PM | Reply

    @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.

  • Milan Negovan

    5/6/2009 7:30:16 AM | Reply

    Alright, alright, you win. Smile I dig "using" with two shovels, though.

  • Miha Markic

    5/6/2009 11:45:17 AM | Reply

    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.

  • Klemen K.

    5/20/2009 12:49:28 PM | Reply

    Hi Miha!

    How about DisposeMe()? Smile