Error: Index was outside the bounds of the array

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?

Jon Skeet
people
quotationmark

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.)

people

See more on this question at Stackoverflow