Search code examples
c#sortedlist

How SortedList Capacity works


I wonder how SortedList capacity property works. In constructor I set capacity equals 2, but I can add more elements. Why?

SortedList<int, string> sortedList = new SortedList<int, string>{ Capacity = 2 };
sortedList.Add(0, "zero");
sortedList.Add(1, "one");
sortedList.Add(2, "two");
sortedList.Add(3, "three");

sortedList.Values.ToList().ForEach(v => Console.WriteLine(v));

Solution

  • The description of initialCapacity parameter of SortedList's constructor says that this parameter specifies the initial capacity of the list, not its final capacity:

    initialCapacity Type: System.Int32 The initial number of elements that the SortedList object can contain.

    This parameter is used to reduce the number of re-allocations when you know the number of elements that you want to add to the list. This parameter does not change the fact that SortedList is a dynamically sized collection capable of expanding when you add elements to it.

    Remarks to the Capacity property of the list provide further clarifications:

    Capacity is the number of elements that the SortedList object can store. Count is the number of elements that are actually in the SortedList.

    Capacity is always greater than or equal to Count. If Count exceeds Capacity while adding elements, the capacity is automatically increased by reallocating the internal array before copying the old elements and adding the new elements.