ArraySegment is throwing System.ArgumentException for apparently no good reason

Pretty simple code snippet:

using System.Text;

byte[] byteArray = new byte[256];
for(int i=0;i<256;i++)
    byteArray[i] = (byte)i;
var segment = new ArraySegment<byte>(byteArray, 167, 170);

but compiled using .NET 6.0, I get an unhandled exception error when I call the ArraySegment constructor. Why? Clearly byteArray has 256 elements. The sub array from indices 167-170 should not be out of bounds.

>Solution :

From the MSDN documents

public ArraySegment (T[] array, int offset, int count);

That means that your array segments

var segment = new ArraySegment<byte>(byteArray, 167, 170);

Is equivalent to

var span = byteArray[167..(167 + 170)];

Which is equivalent to

var span = byteArray[167...337];

Which is clearly out of range.

I think you wanted

var segment = new ArraySegment<byte>(byteArray, 167, 3);

Leave a Reply