Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need to use "using" keyword in every object which implements IDisposable?

I am calling a 3rd party library, where so many class implemented IDisposable.

Do I need to use using pattern on all of them?

like image 602
Adam Lee Avatar asked Feb 09 '12 14:02

Adam Lee


3 Answers

You don't have to, but it is good practice.

It ensures resources are cleaned up properly whether exceptions occur or not.

IDisposable should only be implemented on classes that need to cleanup resources, so ensuring that they do is good practice.

There may be cases that calling Dispose directly instead of a using block will be required (WCF proxies are notorious for this), but this is not the general case.

In short - no one will force you to use them, but you really really should.

like image 143
Oded Avatar answered Oct 22 '22 12:10

Oded


You don't “need” to do it, but you most likely should.

If you don't do that, you can be running out of some resources, or you can even get incorrect results, depending on what exactly does that library do.

But without knowing what exactly does Dispose() do on those objects, you should definitely call it, to avoid unexpected problems. (And you don't have to do that directly, you can use using to do that, as you suggested.)

like image 3
svick Avatar answered Oct 22 '22 13:10

svick


That depends very much on the scope of the variable in question.

Local Scope: using

If the variable is scoped locally, yes, you should enclose relevant code in a using block. Remember, a using block is just syntax sugar for the following, assuming using is enclosing an IDisposable object named obj:

var obj = // ...
try
{
    // ...
}
finally
{
    obj.Dispose();
}

This means that even if an exception is thrown, your object will be disposed.

Class Scope: IDisposable

If your object is scoped at a class level, then no, you should not be enclosing it in a using block. Rather, your class should expose the Dispose method to any code that uses it by implementing IDisposable, and dispose the object there.

Never Use: Finalize

Generally, it is bad practice to transfer disposal responsibility to the garbage collector at any point in this dependency chain by relying on a class's finalizer to dispose its objects. This undermines this difference between Dispose and Finalize: Dispose is for explicit, immediate resource release, while Finalize is more passive. By relying on Finalize to call Dispose, you undermine this separation of purpose. However, this is more a matter of programming style on my part, and represents an opinion--do not take it as a fact. You should research this more on your own--and certainly read the inevitable array of incoming comments on the matter--before taking my advice. I'm sure I missed important exceptions, at the very least.

like image 3
Zenexer Avatar answered Oct 22 '22 14:10

Zenexer