How do I efficiently get a subset of a byte array (first N elements) in C#?

.net, c#

Solution

If you can't change the method signature, then you're stuck. You can't create a "view" over a byte array with type byte[]. The ideal solution for that would be for the operation to either take an `ArraySegment<byte>` or a `byte[]` followed by an offset and a count. If you really can't change the Write method, then unfortunately you're stuck with creating a new array and copying the data to it.

Problem

I have an byte array buffer of max size 1K. I want to write out a subset of the array (the start of the subset will always be element 0, but the length we're interested in is in a variable). The application here is compression. I pass in a buffer to a compression function. For simplicity, assume the compression will lead to data that is equal, or less than 1K bytes. ``` byte[] buffer = new byte[1024]; while (true) { uncompressedData = GetNextUncompressedBlock(); int compressedLength = compress(buffer, uncompressedData); // Here, compressedBuffer[0..compressedLength - 1] is what we're interested in // There's a method now with signature Write(byte[] compressedData) that // I won't be able to change. Short of allocating a custom sized buffer, // and copying data into the custom sized buffer... is there any other // technique I could use to only expose the data I want? } ``` I'd really like to avoid a copy here -- it seems completely unnecessary as all of the data needed is in `buffer` already.

Original source