Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List<> Capacity returns more items than added

There are several properties on List<T> that seem to be related to number of items in the list - Capacity, Count (which is present as a property and a method). This is quite confusing especially compared with Array that has just Length.

I'm using List.Capacity but it gives unexpected result:

List <string> fruits = new List<string>();
fruits.Add("apple");
fruits.Add("orange");
fruits.Add("banana");
fruits.Add("cherry");
fruits.Add("mango");
Console.WriteLine("the List has {0} items in it.", fruits.Capacity);

when I run this the Console displays:

the List has 4 items in it.

I don't understand why its showing a Capacity of 8, when I only added 5 items.

like image 635
Pete Avatar asked Mar 20 '10 23:03

Pete


2 Answers

The Capacity of the list represents how much memory the list currently has set aside for the current objects and objects to be added to it. The Count of the list is how many items have actually been added to the list.

like image 194
Adam Maras Avatar answered Oct 18 '22 12:10

Adam Maras


Here's the full explanation for the Capacity property from MSDN:


Capacity is the number of elements that the List<T> can store before resizing is required, while Count is the number of elements that are actually in the List<T>.

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

The capacity can be decreased by calling the TrimExcess() method or by setting the Capacity property explicitly. When the value of Capacity is set explicitly, the internal array is also reallocated to accommodate the specified capacity, and all the elements are copied.

Retrieving the value of this property is an O(1) operation; setting the property is an O(n) operation, where n is the new capacity.

like image 40
M4N Avatar answered Oct 18 '22 14:10

M4N