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.
how about SafeDispose? I usually add the prefix Safe when I create functions that are designed to handle cases like this.
SafeDispose sounds better indeed.
I would also go for SafeDispose.
The way they usually do it at MS the only option is Dispose2.
π
DisposeNow
SafeDispose — there’s nothing safe about it, really. π
Miha, how about an even shorter variation?
using (someObject as IDisposable)
{
}
If someObject is null in the first place, the compiler bails (see more here: http://aspnetresources.com/blog/the_very_handy_using_statement.aspx)
@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.
Alright, alright, you win. π I dig "using" with two shovels, though.
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.
Hi Miha!
How about DisposeMe()? π