More On IDisposable

C# Add comments

My posts Deterministic Finalization in Garbage-Collected Languages and Rules for Implementing IDisposable are, in my opinion, a fair introduction to the purpose and use of C#’s IDisposable idiom. However, I would like to propose the following additional guideline for the usage of IDisposable:

The class which creates a disposable object is responsible for calling Dispose().

Ridiculously obvious, right? Yet it has some important implications. Consider this quote from Rules for Implementing IDisposable:

If you write a class which contains a member which implements IDisposable, your class must also implement IDisposable and dispose each member in turn in your Dispose() method.

This is only true if your class created the disposable object. If your class was passed the disposable object in the constructor, you should not call its Dispose() method. Similarly, if you are writing a class which wraps a Stream and provides additional functionality (e.g. BufferedStream or GZipStream), you should not call the underlying Stream’s Dispose() method if you did not create the underlying Stream yourself.

This implies that, in general, passing an object to a constructor of another class is not a transfer of ownership. (For further reflection: Are there cases where this isn’t true? Is there an alternative idiom to express the concept of transfer of ownership?)

Comments are closed.

WP Theme & Icons by N.Design Studio
Entries RSS Comments RSS Log in