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?
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]);
}
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)
.
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