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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With