Should classes that are passed references to IDisposable objects be IDisposable as well and set them to null when disposed?
I think the question says it al开发者_C百科l.
Thanks.
They should implement IDisposable
if the object owns that resource. There's generally no need to set things to null, although it does no harm.
If you don't own the resource, then clearly you shouldn't dispose of it, and you don't need to implement IDisposable
. In my experience it's relatively rare that I have a member variable for a disposable resource which I don't own in my classes though...
"Holding a reference" is not the real criterium. When an object logically 'owns' an IDiposable object then Yes, it should implement IDisposable to call Dispose for all owned Disposable objects.
But it should not implement a destructor (Finalizer) .
Setting to null isn't necessary, but you should call .Dispose()
on all of those objects from the parent class's .Dispose()
.
EDIT: IF AND ONLY IF your class was responsible for creating those objects.
This a good practice yes. When the dispose of such a class is called, it's a good idea to call Dispose on all referenced objects as well.
Yes they should if the reference is owned by the class, FxCop / MS code analysis even have a check for it.
If your class creates the disposable object then your class is responsible for cleaning them up. Since your class won't know when to cleanup unless something tells it to (i don't count destructors) it is the easiest way to make your class implement IDisposable.
If your class uses, but does not create, disposable objects then you should leave cleaning up to the creator of those objects.
精彩评论