Reset or Clear .NET MemoryStream

Since a MemoryStream is essentially a byte array with an index (and some other supporting members) clearing the byte array and resetting the index can be considered resetting and clearing the MemoryStream. If the initial state of a MemoryStream is a zeroed array with a position of zero then an example of a MemoryStream reset may be:

public static void Clear(this MemoryStream source)
{
  byte[] buffer = source.GetBuffer();
  Array.Clear(buffer, 0, buffer.Length);
  source.Position = 0;
  source.SetLength(0);
}

It is incorrect to say that MemoryStream.SetLength alone resets or clears the MemoryStream since SetLength only clears the internal buffer array if the length exceeds the current buffer's length.

Reinitializing a MemoryStream is a valid approach but less efficient. One benefit of reinitializing the MemoryStream would be to guarantee that the stream was never closed. Once the MemoryStream is closed it can no longer be changed. If you can ensure that the MemoryStream instance isn't closed then clearing the buffer may be the way to go.


Why do you need resetting memory stream? You always can create a new one. Or you can use:

memoryStream.SetLength(0);