3

I'm writing a piece of code which uses nested stream:

using (var zip = new ZlibStream(new MemoryStream(to_be_unziped), CompressionMode.Decompress))
{

}

Is it fine? Or should I write it as:

using (var memory_stream = new MemoryStream(to_be_unziped))
using (var zip = new ZlibStream(memory_stream, CompressionMode.Decompress))
{

}
12
  • For readability I use the second one. Technical there is no difference between both versions Commented Jun 11, 2019 at 5:42
  • 1
    There is nothing wrong with the 1st method, but I think 2nd one is more readable but in the second one it should be just memory_stream not var memory_stream Commented Jun 11, 2019 at 5:42
  • @TheLastStark Oh it's my typo. I've fixed it. Commented Jun 11, 2019 at 5:43
  • So in the 1st method, when the outer stream gets closed, the inner one will also be closed, right? Commented Jun 11, 2019 at 5:44
  • 1
    You don't need to dispose MemoryStream. Commented Jun 11, 2019 at 5:46

1 Answer 1

2

When you create a ZlibStream and pass in MemoryStream it holds a reference to it.

When it's Disposed, it calls Close on that reference, which in turn will hit the Dispose plumbing of abstract Stream class.

protected override void Dispose(bool disposing)
{
    try
    {
        if (!_disposed)
        {
            if (disposing && (this._baseStream != null))
                this._baseStream.Close();
            _disposed = true;
        }
     }
     finally
     {
        base.Dispose(disposing);
     }
}

It's worth noting, that a MemoryStream has no unmanaged resources anyway, and actually doesn't need to be Disposed, it doesn't override the Close of the Stream class.

Stream also checks if Dispose has already been called. Meaning in most cases, you only have to Dispose the stream you are working with.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.