Why does List<T> blow up when i index into it?
I created a list as a class level field like this:
private readonly IList<int> _intCol = new List<int>();
I then index into it and it blows up with the exception below:
_intCol[0] = 0;
Exception:
Index was out of range. Must be non-negative and less than the size of the开发者_StackOverflow collection.Parameter name: index
At this point, _intCol
is a list of the size 0, it does not have an element on the first position.
You can use _intCol.Add(0);
.
See also:
List<T>.Add(T)
List<T>.Insert(int, T)
If you do want to insert elements that way, you can use a Dictionary<int,int>
, but note that your elements are not ordered - you just map numbers to numbers. For example:
Dictionary<int, int> integers = new Dictionary<int, int>();
integers[0] = 13;
integers[42] = 14;
integers
now has two items, in no particular order:
{42: 14, 0: 13}
If you haven't populated the list with any elements, then trying to reference element 0 will fail just like that. You should check the Count first, and not reference any element index greater than Count-1.
精彩评论