Search code examples
.netmemorystreamgetbuffer

When is GetBuffer() on MemoryStream ever useful?


I've known that GetBuffer() on a MemoryStream in C#/.NET has to be used with care, because, as the docs describe here, there can be unused bytes at the end, so you have to be sure to look only at the first MemoryStream.Length bytes in the buffer.

But then I ran into a case yesterday where bytes at the beginning of the buffer were junk! Indeed, if you use a tool like reflector and look at ToArray(), you can see this:

public virtual byte[] ToArray()
{
    byte[] dst = new byte[this._length - this._origin];
    Buffer.InternalBlockCopy(this._buffer, this._origin, dst, 0,
        this._length - this._origin);
    return dst;
}

So to do anything with the buffer returned by GetBuffer(), you really need to know _origin. The only problem is that _origin is private and there's no way to get at it...

So my question is - what use is GetBuffer() on a MemoryStream() without some apriori knowledge of how the MemoryStream was constructed (which is what sets _origin)?

It is this constructor, and only this constructor, that sets origin - for when you want a MemoryStream around a byte array starting at a particular index in the byte array:

public MemoryStream(byte[] buffer, int index, int count, bool writable, bool publiclyVisible)

Solution

  • If you really want to access the internal _origin Value, you may use the MemoryStream.Seek(0, SeekOrigin.Begin) call. The return Value will be exactly the _origin Value.