tags:

views:

192

answers:

4

What is the default capacity of a List?

+3  A: 

The default capacity of List is 4 items (after you insert an initial item, otherwise it's of 0 size)

var list = new List<int>();
list.Add(1);

Assert.AreEqual(4, list.Capacity);
Elisha
Yes, it grows exponentially like that, 4, 8, 16, 32, 64... but default is definitely 0.
David Hedlund
+11  A: 

Why don't you just try it?

Console.WriteLine("Default capacity of a List: " + new List<int>().Capacity);

This answer will work on all versions of .NET that have List. On my version, it happens to be 0.

Mark Byers
+9  A: 

According to the sample on the MSDN parameterless constructor documentation, the initial capacity of a list created with:

List<string> x = new List<string>();

is 0. As far as I can tell, this isn't documented as a guarantee, nor is the resize policy documented (i.e. it may currently double with a minimum of 4, but in .NET 5.0 it could triple with a minimum of 128.) You shouldn't rely on this behaviour, basically.

Jon Skeet
Actually it states that it "is empty and has the default initial capacity". Using Reflector the default is revealed as 4.
Brian Rasmussen
@Brian: Nope, the default initial capacity is 0 in this case. 4 is the first capacity for a list which has to have elements. The important thing is that it's *not documented* to be either 0 or 4. It could be 100 in the next version without breaking any documented behaviour.
Jon Skeet
@Brian: Whatever the documentation says, it starts with 0 according to the `Capacity` property.
Thorarin
@Jon: I completely agree that this is an implementation detail, which is the important point here. And I see your point. 4 is the "default capacity" once something is actually added to the list.
Brian Rasmussen
+2  A: 

Actually, it starts with a Capacity of 0. When you add the first element, the current implementation allocates a capacity of 4. After that, the capacity keeps doubling if expansion is needed, to guarantee amortized O(1) operation.

Keep in mind that this is the current behavior. You shouldn't rely on it to be the case. This should demonstrate the current behavior:

List<int> list = new List<int>();
int capacity = list.Capacity;
Console.WriteLine("Capacity: " + capacity);

for (int i = 0; i < 100000; i++)
{
    list.Add(i);
    if (list.Capacity > capacity)
    {
        capacity = list.Capacity;
        Console.WriteLine("Capacity: " + capacity);
    }
}
Thorarin