Matteo Sberna
Matteo Sberna

Reputation: 13

adding element in a list throws ArgumentOutOfRangeException

My code throws this:

ArgumentOutOfRangeException: Argument is out of range.
Parameter name: index error

When it finds an element in a list that have a count less that a specific number. any ideas on how to correct the code?

I've added debug.log code everywhere to determine exactly where the error happens, because no error is underlined by Visual Studio.

List<int> emptyRows = new List<int>();
for (int j = 0; j < gridPositions.Count; j++) // try to find if a row is still empty
                {
                    Debug.Log("gridPositions[" + j + "].Count is " + gridPositions[j].Count);
                    Debug.Log("columns are" + columns);
                    if (gridPositions[j].Count == columns)
                    {
                        Debug.Log("trying to add to emptyrows");
                        emptyRows.Add(j);
                        Debug.Log("added to emptyrows and its count is " + emptyRows.Count);
                    }
                    else
                    {
                        Debug.Log("found an occupied row at row " + j);
//ERROR STRIKES HERE
                    }
                    Debug.Log("emptyRows is " + emptyRows[j]);
                    Debug.Log("emptyRows count is " + emptyRows.Count);
                }

I expect the emptyRows to track and record all unoccupied rows, but when it fills an occupied row, it not proceeds whit the for loop and stops.

Upvotes: 1

Views: 38

Answers (1)

npo
npo

Reputation: 1060

You are only adding to emptyRows if (gridPositions[j].Count == columns)

But you are accessing the emptyRows[j] on every value of j

So the emptyRows ends up having less items then the value of j is

Upvotes: 1

Related Questions