Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Lists: initialize with size, why then can't use [] access until after .Add()?

Tags:

arrays

c#

list

This works fine with an array:

int[] a = new int[10];
for (int i = 0; i < 10; i++)
{
    a[i] = i;
}

But this throws an ArgumentOutOfRangeException with a list:

List<int> a = new List<int>(10);
for (int i = 0; i < 10; i++)
{
    a[i] = i;
}

Why is that? I thought that lists used arrays internally.

like image 684
wes Avatar asked Nov 29 '22 03:11

wes


1 Answers

You are initializing the capacity, not the size. The count will still be zero. Initializing the capacity allows an optimization to size the internal data structure (an array) when you know the maximum size when creating the list. This keeps the internal array to a known size and prevents internal array re-sizing as you add the known number of elements.

like image 200
Tim Lloyd Avatar answered Dec 05 '22 14:12

Tim Lloyd