Foo
Foo

Reputation: 4596

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?

Upvotes: 7

Views: 3609

Answers (5)

Jeremy Cook
Jeremy Cook

Reputation: 22063

Almost always yes, but here is an example of when disposing something borrowed can cause problems. I created a disposable repository with two constructors, one that takes a DbContext, and another default constructor that creates the DbContext itself. I ran into instances when my repository would be disposed, triggering the disposal of the DbContext (because I told it to), and that would sometimes cause problems because I still needed the DbContext that had been passed in elsewhere in the code.

In this case, the repository creates the DbContext and must take responsibility for it and dispose of it because no other code can, but when the DbContext is passed in by some other code then disposing of the DbContext should be the responsibility of the code that created it.

Upvotes: 1

Habib
Habib

Reputation: 223247

Make sure to Dispose the items before they lose scope.

The best way is to use using statement, or you can manually call Dispose, but before it loses scope and becomes eligible for garbage collection.

You may see: CA2000: Dispose objects before losing scope

If a disposable object is not explicitly disposed before all references to it are out of scope, the object will be disposed at some indeterminate time when the garbage collector runs the finalizer of the object. Because an exceptional event might occur that will prevent the finalizer of the object from running, the object should be explicitly disposed instead.

Upvotes: 4

Omaha
Omaha

Reputation: 2292

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.

Upvotes: 17

user240141
user240141

Reputation:

Not mandatory in all scenarios, but its a good practice to dispose an object. If you dont want to do it for each object, use using {} on which disposable is implemented.. It will take care of diposing the object when the code block is over.

Upvotes: 0

Tim S.
Tim S.

Reputation: 56536

As a general rule, yes. The easiest way to do this is usually with the using statement.

Upvotes: 1

Related Questions