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))
{
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With