Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error: Index was outside the bounds of the array

Tags:

c#

When I'm running this code, I'm getting error

Index was outside the bounds of 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 anyone help me out, please?

like image 820
John.P Avatar asked Sep 29 '22 03:09

John.P


1 Answers

You're using lines[i + 3] in the loop, but your check only ensures that i + 2 is in range - and the fact that you're using 4 values in the loop rather than 4 makes it look like this should probably 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]
    });
}

(That's assuming you want to start on the 4th item, as before - you should check what you want the initial value of i to be.)

like image 75
Jon Skeet Avatar answered Oct 09 '22 16:10

Jon Skeet