Just a learner
Just a learner

Reputation: 28592

C# nested stream with using statement, should I use two using?

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))
{

}

Upvotes: 3

Views: 681

Answers (1)

TheGeneral
TheGeneral

Reputation: 81513

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.

Upvotes: 2

Related Questions