Search code examples
c#.net.net-4.0usingidisposable

Multiple using block, is this code safe?


Code snippet is as follows

 public static string ToCompressedBase64(this string text)
    {
        using (var memoryStream = new MemoryStream())
        {
            using (var gZipOutputStream = new GZipStream(memoryStream, CompressionMode.Compress))
            {
                using (var streamWriter = new StreamWriter(gZipOutputStream))
                {
                    streamWriter.Write(text);
                }
            }
            return Convert.ToBase64String(memoryStream.ToArray());
        }
    }

As far as I know, if class contains field which is IDisposable then It should implement IDisposable itself and take care of disposal of the owned object, so with this assumptions, after disposal of streamWriter the gZipOutputStream and memoryStream will also be disposed. But we still need not disposed memoryStream to invoke toArray() method on It.
So the question is, Is calling ToArray() method on memoryStream at the end safe?


Solution

  • If I understand your question correctly, you are asking if it's safe to call ToArray() on a MemoryStream after it has been disposed.

    If so, then yes, it's safe. The documentation specifies:

    This method works when the MemoryStream is closed.

    EDIT: And in case it's not clear whether closed also means disposed, you can also look at the source code for the Dispose method (Note: The link is to Stream.Dispose() since MemoryStream doesn't override the Dispose method):

    public void Dispose()
    {
        /* These are correct, but we'd have to fix PipeStream & NetworkStream very carefully.
        Contract.Ensures(CanRead == false);
        Contract.Ensures(CanWrite == false);
        Contract.Ensures(CanSeek == false);
        */
    
        Close();
    }
    

    As you can see, calling Dispose() does nothing more than calling Close().