Capacity of a SortedList in C# – Programming, Pseudocode Example, C# Programming Example
C# Collection

Capacity of a SortedList in C#

SortedList.Capacity Property is used to get or set the capacity of a SortedList object.

Syntax:

Return Value: This property returns the number of elements of type System.Int32 that the SortedList object can contain.

Exceptions:

  • ArgumentOutOfRangeException: If the value assigned is less than the current number of elements in the SortedList object.
  • OutOfMemoryException: If there is not enough memory available on the system.

Capacity Vs Count:

  • Count is always less than the Capacity. While adding the elements, if Count exceeds Capacity then the Capacity will increase automatically by reallocating the internal array before copying the old elements and adding the new elements.
  • Capacity is the number of the elements which the List can store before resizing of List needed. But Count is the number of the elements which are actually present in the List.
  • If the Capacity is much larger than the Count the user can decrease capacity by either calling the TrimExcess method or explicitly setting the Capacity to a lower value.
  • If the Capacity is settled explicitly then the internal array is also reallocated to accommodate the specified capacity, and all the elements are copied.
  • Retrieving the value of the Capacity property is an O(1) operation while setting the Capacity is an O(n) operation, where n is a new capacity.

Below given are some examples to understand the implementation in a better way:

Example 1:

Output:

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.