1

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?

Łukasz Kosiak
  • 513
  • 6
  • 22
  • 2
    Is there a reason you need to call it at the end? I'd call it immediately following the streamWriter.Write. – Kevin Aug 25 '16 at 12:34
  • 3
    @Kevin The `GZipStream` might not have processed all the data after calling `StreamWriter.Write`. – Dirk Aug 25 '16 at 12:46

1 Answers1

6

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().

sstan
  • 35,425
  • 6
  • 48
  • 66