Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I dispose all disposable objects?

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?

like image 420
Foo Avatar asked Sep 12 '13 18:09

Foo


1 Answers

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.

like image 167
Omaha Avatar answered Oct 11 '22 19:10

Omaha