How do I Marshal out a Subset byte[] Array in Managed Code?
<p>Consider the following method (used in a factory method):</p>

<pre><code>private Packet(byte[] rawBytes, int startIndex)
{
    m_packetId = BitConverter.ToUInt32(rawBytes, startIndex);
    m_dataLength = BitConverter.ToUInt16(rawBytes, startIndex + 4);
    if (this.Type != PacketType.Data)
        return;
    m_bytes = new byte[m_dataLength];
    rawBytes.CopyTo(m_bytes, startIndex + Packet.HeaderSize);
}
</code></pre>

<p>The last two lines of code strike me wasteful.  Allocating more memory and populating it with values from memory seems silly.</p>

<p>With unmanaged code, something like this is possible:</p>

<pre><code>    m_bytes = (rawBytes + (startIndex + Packet.HeaderSize));
</code></pre>

<p>(I didn't run it through a compiler so syntax is probably off, but you can see it's just a matter of pointer manipulation.)</p>

<p>I ran into a similar problem the other day when an API returned a byte[] array that was really a short[] array.</p>

<p>Are these types of array permutations just the cost of using managed code or is there a new school of thinking that I'm just missing?</p>

<p>Thanks in advance.</p>
