Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does list insertion fail when sufficient size is provided on construction?

Tags:

c#

list

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?

like image 488
Erix Avatar asked Jan 04 '12 16:01

Erix


2 Answers

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 the List<T> can hold. As elements are added to a List<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]);
}
like image 132
user7116 Avatar answered Nov 03 '22 05:11

user7116


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).

like image 40
TheBoyan Avatar answered Nov 03 '22 03:11

TheBoyan