Error: index was outside array

When I run this code, I get an error

The index was outside the array.

for (var i = 9; i + 2 < lines.Length; i += 3) { Items.Add(new ItemProperties { Item = lines[i], Description = lines[i + 1], Quantity = lines[i + 2], UnitPrice = lines[i + 3] }); } 

Can someone help me please?

+5
source share
1 answer

You use lines[i + 3] in the loop, but your check only ensures that i + 2 is in the range - and the fact that you use 4 values ​​in the loop, not 4, looks like this: to be:

 for (var i = 12; i + 3 < lines.Length; i += 4) { Items.Add(new ItemProperties { Item = lines[i], Description = lines[i + 1], Quantity = lines[i + 2], UnitPrice = lines[i + 3] }); } 

(Suppose you want to start with the 4th element, as before - you must verify that you want the initial value of i be.)

+4
source

All Articles