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.
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.
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