I am calling a 3rd party library, where so many class implemented IDisposable.
Do I need to use using pattern on all of them?
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.
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.)
That depends very much on the scope of the variable in question.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With