Назад к вопросам
Junior
256
questionbank
В чем разница между свойствами Count и Capacity в коллекциях C#?
Sobes Copilot
Получайте ответы в реальном времени
Ответ от нейросети
sobes.tech AI
Count - количество фактически содержащихся элементов в коллекции.
Capacity - максимальное количество элементов, которое коллекция может вместить до того, как потребуется перераспределение памяти.
Например, для List<T>:
System.Collections.Generic.List<int> numbers = new System.Collections.Generic.List<int>();
// Initially, Count is 0, Capacity is usually non-zero (implementation specific, often 0 then grows)
// numbers.Count == 0
// numbers.Capacity == ?
numbers.Add(1);
numbers.Add(2);
// Count is now 2
// numbers.Count == 2
// Capacity may be greater than 2 to accommodate future additions without frequent resizing
// numbers.Capacity == ? (>= 2)
numbers.Add(3);
numbers.Add(4);
numbers.Add(5);
// Count is now 5
// numbers.Count == 5
// Capacity will be increased if needed to accommodate these additions
// numbers.Capacity == ? (>= 5, typically doubles from previous capacity)