Search code examples
c#streamdisposeidisposable

Disposing derived stream containing streams


I have the following class derived from stream:

public class EncryptedStream : Stream
{
    private readonly SymmetricAlgorithm _engine;
    private readonly CryptoStream _cryptoStream;
    private readonly Stream _inputStream;

   //Standard overrides of stream
}

I am looking for a way to the dispose the base stream and all streams and resources within this class. I have read about the dispose pattern a bit, and since stream already implements IDisposable, my thought would be to dispose in this class I would do the following:

protected override void Dispose(bool disposing)        
{
    if (disposing)
    {
       _engine.Dispose();
       _cryptoStream.Dispose();
       _inputStream.Dispose();
    }
}

This should get called when disposing of the base stream since the base stream IDisposable calls Close() which calls Dispose(true).

This appears to work, is there any downfalls to this approach? And also, do I need to call base.Dispose(disposing) after the If statement? I don't think so as that is essentially already being done by calling Dispose on the base stream in the first place correct?

Is there any other less convoluted way to go about this disposing as this took me a while to understand.


Solution

  • What you have is good. No need to call the Stream::Dispose(bool), it is a virtual method with an empty body.

    I also recommend you keep this link handy, it lists a lot of Dos and Don'ts for the Dispose Pattern.

    (Copied from Stream.cs)

    /// <summary>Releases the unmanaged resources used by the <see cref="T:System.IO.Stream" /> and optionally releases the managed resources.</summary>
    /// <param name="disposing">
    /// <see langword="true" /> to release both managed and unmanaged resources; <see langword="false" /> to release only unmanaged resources.</param>
    [__DynamicallyInvokable]
    protected virtual void Dispose(bool disposing)
    {
    }