All initial sizes give a hint of implementation in order to have at least a given capacity . It does not create a list populated with N entries by default; my attention:
Initializes a new instance of the List<T> class , which is empty and has the specified initial capacity.
If you continue to record MSDN in the Remarks section, you will find out why this constructor overload is provided (again, my emphasis):
The capacity of a List<T> is the number of elements that List<T> can hold. Since the elements are added to the List<T> , the capacity automatically increases in accordance with the need to redistribute the internal array.
If the size of the collection can be estimated, specifying the initial capacity eliminates the need for several resizing operations when adding items to the List<T> .
In short, List<T>.Count does not match List<T>.Capacity ("If the number exceeds the Capacity when adding items, the capacity increases ...").
You get an exception, because the list only logically contains the elements that you add, changing the capacity does not change the number of logically stored elements. If you were to set List<T>.Capacity less than List<T>.Count , we can test this behavior in 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 create the behavior you are looking for:
public static List<T> CreateDefaultList<T>(int entries) { return new List<T>(new T[entries]); }
source share