Deleting bug in List?


I tried to delete last element in inpInnov using inpInnov.RemoveAt(inpInnov.Count - 1);. However I was getting an error “ArgumentOutOfRangeException”, then I wrote%

Debug.Log(inpInnov.Count - 1);
inpInnov.RemoveAt(0);

I got this(even error did not change)

Here are some notes on IndexOutOfRangeException and ArgumentOutOfRangeException:

http://plbm.com/?p=236

Steps to success:

  • find which collection it is and what line of code accesses it <— (critical first step!)
  • find out why it has fewer items than you expect
  • fix whatever logic is making the indexing value exceed the collection size

Remember also:

  • a collection with ZERO elements cannot be indexed at all: it is empty
  • you might have more than one instance of this script in your scene/prefab
  • the collection may be used in more than one location in the code
  • indices start at ZERO (0) and go to the count / length minus 1.

This means with three (3) elements in your collection, they are numbered 0, 1, and 2 only.

The collection has zero elements. You can’t remove an element at index zero when there is no element at index zero.

And @Kurt-Dekker, If i write Debug.Log(inpInnov.Count);, it prints “1”

Your code and your description has some conflicting information. This makes it really difficult to tell what you’re actually doing. You said you want to remove the last element but the code you have shown removes the first while printing the index of the last one. We don’t know if the two log messages do actually correspond to those two lines, have you checked the stacktrace?

Where / when is this code executed? Does the error happen consistently / can be repeated consistently? Is there any funky multi-threading going on?

We can not debug your code for you, especially when we don’t have the code nor the context. List.RemoveAt certainly does not have a bug.

Run this code and report what you got:

var list = new List<int> { 123 };
Debug.Log($"{list.Count - 1} - {list[list.Count - 1]}");
list.RemoveAt(0);
Debug.Log(list.Count);

I suspect that you are confusing it with an exception thrown from a different location.


This works