Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading