Many objects in .NET (SQLCommand
for instance) implement IDisposable
. As a general rule, if I create an instance of an IDisposable
object, should I always dispose it?
Yes, unless you're receiving it from a caller who needs it once you're done or has taken responsibility for calling Dispose()
. The important thing is that someone calls Dispose()
and if you are being passed an IDisposable
instance, there needs to be an understanding ("contract") about whether you are taking ownership for it (and thus need to dispose it) or whether you are "borrowing it" and the caller will use/dispose it upon your return. These are the types of things good APIs have in their documentation.
If you are instantiating the object, make it easy on yourself to automatically dispose by using using
.
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