user1920556
user1920556

Reputation: 23

Getting an "ArgumentOutOfRangeException" error but don't know how?

my code's throwing up an out of range error while I'm looping through a List, but I don't know why. Here's my code:

        for(int neighborCounter = neighborList.Count - 1; neighborCounter >= 0; neighborCounter--)
        {
            for(int toBeCheckedCounter = toBeChecked.Count - 1; toBeCheckedCounter >= 0; toBeCheckedCounter--)
            {
                Vector2 tile1 = neighborList[neighborCounter];
                Vector2 tile2 = toBeChecked[toBeCheckedCounter];

                if(tile1 == tile2)
                {
                    neighborList.Remove(neighborList[neighborCounter]);
                }
            }
        }

If you guys need any more context let me know. The error appears on the line where tile1 is declared. It looks like I'm trying to access an element that neighborList doesn't contain.

Upvotes: 1

Views: 109

Answers (2)

Tyress
Tyress

Reputation: 3653

Your neighborCounter is an outer loop. If you remove enough from the neighborList, since neighborCounter is not moving while toBeCheckedCounter moves, there can be a point where neighborCounter = neighborList.Count, which will trigger your ArgumentOutOfRangeException.

I suggest you avoid removing in a loop or a foreach. You can list all of the items you will be removing and do it after,i.e.

if(tile1 == tile2)
{
  itemsToRemove.Add(neighborList[neighborCounter]); // itemsToRemove can be a HashSet
}

Upvotes: 4

Armin
Armin

Reputation: 232

Tyress is right with his explanation: https://stackoverflow.com/a/35546304/4927547

Another way you can avoid getting ArgumentOutOfRangeException would be rewriting your code like this:

foreach (Vector2 neighbor in neighborList)
{
    foreach (Vector2 toBeCheckedItem in toBeChecked)
    {
        if (neighbor == toBeCheckedItem)
        {
            neighborList.Remove(neighbor);
        }
    }
}

Another way

foreach (Vector2 toBeCheckedItem in toBeChecked)
{
    if (neighborList.Contains(toBeCheckedItem))
    {
        neighborList.Remove(toBeCheckedItem);
    }
}

Upvotes: 0

Related Questions