I have an empty list defined to hold 120 values, I want to insert an element at index(45), even though the list is currently empty. Is this possible?
public List<Ticket> Tickets = new List<Ticket>(120);
Tickets.Insert(45,ticket); // Here I am getting the ArgumentOutOfRangeException
You set the initial internal capacity of the list to 120. The list is still empty.
List<T>
can hold any number of items. Internally, it uses an array to store them. If the array gets full, the list will allocate a new, larger one. If you know the number of items in advance, you can set the size of the internal array when you construct the list. This way you can avoid unnecessary memory allocation.
You could use an array:
Ticket[] tickets = new Ticket[120];
tickets[45] = ticket
or a Dictionary<int, Ticket>
Dictionary<int, Ticket> tickets = new Dictionary<int, Ticket>();
tickets.Add(45, ticket);
or create a List<Ticket>
holding 120 nulls:
List<Ticket> tickets = Enumerable.Repeat(default(Ticket), 120).ToList();
120
is defined as the capacity of the list - not the really existing elements. So in this case your list contains 0 elements at insert.
When you try to insert a element at position 45 into a empty list - a ArgumentOutOfRangeException makes sense
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With