Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

}
like image 351
Just a learner Avatar asked Nov 30 '25 00:11

Just a learner


1 Answers

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.

like image 106
TheGeneral Avatar answered Dec 01 '25 15:12

TheGeneral



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!