I have this code:
List<string> list = new List<string>(30);
list.Insert(1, "string 1");
list.Insert(10, "string 10");
list.Insert(5, "string 5");
The run-time is crashing on sting 10 with exception Index must be within the bounds of the List
What I can’t understand is that I have defined a list with 30 items, so why does this crash and what is the point of defining the 30 if I can’t add an items in such way?
The list is still empty when initialized. The parameter ’30’ means it will simply have the capacity of 30 items.
If you insist on using a list instead of an array, you must first add 30 items and then you can set them with their appropriate index.
The easiest way to do this would be:
Also note that when you’re using
Insert, it will basicallyAddthe item to a certain index, so the number of items in the list will grow.