If we have the following variable declaration:
List list = new List(5);
Why does this:
list.insert(2, 3);
Because insert assumes that the list actually has that many items already inserted- capacity is not the same thing as size. Initializing the list with a given capacity just sets the size of the internal array- it is an optimization to prevent array resizes when you know the number of items that you are going to be inserting.
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 N
default entries; emphasis mine:
Initializes a new instance of the
List<T>
class that is empty and has the specified initial capacity.
If you continue through the MSDN entry to the Remarks section, you'll find why this constructor overload is provided (again, emphasis mine):
The capacity of a
List<T>
is the number of elements that theList<T>
can hold. As elements are added to aList<T>
, the capacity is automatically increased as required by reallocating the internal array.If the size of the collection can be estimated, specifying the initial capacity eliminates the need to perform a number of resizing operations while adding elements to the
List<T>
.
In short List<T>.Count
is not the same as List<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>.Capacity
to less than List<T>.Count
we can test this behavior going the other direction:
Unhandled Exception: System.ArgumentOutOfRangeException: capacity was less than
the current size.
Parameter name: value
at System.Collections.Generic.List`1.set_Capacity(Int32 value)
To perhaps create the behavior you're looking for:
public static List<T> CreateDefaultList<T>(int entries)
{
return new List<T>(new T[entries]);
}
Use
listItem.Addrange(number);
Internally a List(T) is implemented using an array in the background. When you initialize the list that way you are just setting the size of the underlying array which resizes as the list grows. Thus, you are initializing the initial capacity. It doesn't mean that your list has that many elements.
You add elements to the list by first initializing it and then add elements to it with .Add(item)
.
The size in the constructor tells it how much to allocate for the background array - it is still, however, empty (just: empty with a certain amount of initial space).
You can ony insert into the used part of the list, or at the end.
The List(int) constructor specifies initial capacity of the list. It does not specify the number of initial elements. Upon construction a list is empty so, any insertion can only be done at index 0.