.NET's MemoryStream and buffer slice

.NET's MemoryStream is a very convenient class. It allows you to use a byte[] array as storage, while accessing it via standard Stream API. Among other things, it allows you to work with a section of a larger byte array, which is very handy when different actions need to be taken for different slices.

Unfortunately, when it comes to access the raw buffer stored in a MemoryStream instance, there is no way to know which position the stream considers as its beginning. Of course, internally this information is stored, however it is a private member and as such is inaccessible to the end user. And this is extremely inconvenient. A number of workarounds can be applied, but they all boil down to having to track this information yourself. Arguably the easiest way is to derive a new class from MemoryStream and add a public property to store the offset in the underlying byte array. For specific applications, more access methods and properties can be provided, to increase code reuse and security. Hopefully, Microsoft will address this shortcoming of MemoryStream in the future.

Add new comment