List<T> in depth
Learn List<T>'s _capacity and AddRange behavior.
List<T> in depth
A List<T> tracks two sizes: Count is the number of items it holds, Capacity is the size of the backing array. As you add items Count grows; when the array is full Capacity doubles and a new array is allocated.
Use AddRange to append a whole collection at once: list.AddRange(new[] { 4, 5, 6 });. This is faster than adding one by one in a loop. TrimExcess releases unused capacity. These three members are the key to managing a list consciously.
AddRange and TrimExcess
AddRange takes an IEnumerable<T> and appends all items in a single pass. With list.AddRange(otherList) the backing array grows once, not per item.
If you shrunk a large list, call TrimExcess() to free unused capacity. But if the list is nearly full the call is a no-op. For performance it is best to set capacity up front: new List<int>(100).
Exercise Add items with AddRange
The list below has three items. Use AddRange to add 4, 5, 6. Then print Count and Capacity on separate lines.
Show example solution
Add three items with AddRange, then print Count and Capacity separately.
Example solution:
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
var list = new List<int>(10);
list.Add(1);
list.Add(2);
list.Add(3);
list.AddRange(new[] { 4, 5, 6 });
Console.WriteLine(list.Count);
Console.WriteLine(list.Capacity);
}
}
Test yourself
-
What does Capacity return?
- Allocated total space
- Item count
- First item
- Last item
Show answer
Allocated total space — Correct. Capacity returns the backing array size; Count returns the item count.
-
Complete the AddRange call
list.AddRange(new[] {____});Show answer
list.AddRange(new[] {4, 5, 6}); -
Match each member to its description
- Count
- Item count
- Capacity
- Allocated space
- AddRange
- Bulk add
- TrimExcess
- Free unused space