If we have the following variable declaration:
List<int> list = new List(5);
Why does this:
list.insert(2, 3);
fail with the following error:
Index must be within the bounds of the List.
What’s the point of providing the initial size?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
All the initial size does is provide a hint to the implementation to have at least a given capacity. It does not create a list filled with
Ndefault entries; emphasis mine:If you continue through the MSDN entry to the Remarks section, you’ll find why this constructor overload is provided (again, emphasis mine):
In short
List<T>.Countis not the same asList<T>.Capacity("If Count exceeds Capacity while adding elements, the capacity is increased…").You receive the exception because the list only logically contains the items you add, changing the capacity does not change the number of items logically stored. If you were to set
List<T>.Capacityto less thanList<T>.Countwe can test this behavior going the other direction:To perhaps create the behavior you’re looking for: