views:

113

answers:

3
+3  Q: 

IDisposable chain

If I implement a object with IDisposable, should all objects that own that object implement it as well, even if they have no other resources to release?

+11  A: 

Yes. You need to dispose of them, in order to have your member variables get disposed correctly.

Any time you encapsulate an IDisposable class, you should make your class IDisposable. In your Dispose method, you should dispose your encapsulated resources. Basically, treat them the same way you would treat a native resource.

Reed Copsey
Only you cannot assume the order in which objects get disposed, if induced by the GC finalizer thread.
Cecil Has a Name
True -but I'm not sure how this is relevant. If you wrap your class and make it disposable, you CAN control the order in which each encapsulated resource is disposed.
Reed Copsey
+1  A: 

If you want deterministic disposal, ultimately some client needs to call Dispose or wrap the calls in a "using" block. To trickle down to your object, that might require that the owner implement IDisposable as well.

You shouldn't rely on the garbage collector to free any time-dependent resources.

Eric Nicholson
This isn't really an unmanaged resources issue. Objects that own unmanaged resource will 1) use `SafeHandle`s or 2) use a user-defined finalizer to release the unmanaged resources. While this is non-deterministic, the garbage collector *is* able to properly release the unmanagaed resources. The primary benefit of proper `IDisposable` chains is timely "close", "end", or "release" of resources sensitive to the issue, such as (but definitely not limited to) I/O.
280Z28
Noted. Thanks.
Eric Nicholson
A: 

nop, they just need to use that class with a "using" statement to make sure they dispose that object properly, but those objects themselves don't need to implement IDisplosable

BlackTigerX
If another class owns an disposable object, it should also implement IDisposable. Otherwise, the owning class has no way to allow callers to dispose of it, and consequently, the disposable resources it owns internally.
Scott Dorman
it just depends on how the class uses the object internally
BlackTigerX
I use the word "own" specifically to mean "has a member variable of specified type", so no this doesn't work. I use the work "uses" for what you're talking about.
C. Ross