Hi today I stumbled over a thing with the List<T>(Int32)
. I thought the behaviour would be the same in following examples:
1.
var myList = new List<string>(5);
myList[1] = string.Empty;
2.
var myArray= new string[5];
myArray[1] = string.Empty;
The first example fails and I get a 'System.ArgumentOutOfRangeException'. The second example works well.
So I tried .Count
on the list and it says its 0, where as when I put .Length
at the array it says 5.
In MSDN it says:
Initializes a new instance of the List class that is empty and has the specified initial capacity.
I thought this means the list has the initial size I pass in. Why isn't this the case?
Thanks in advance!
Count is how much elements actually in the list, Capacity is the size of the internal data structure. It's intended to handle large list that you already know the size beforehand, so it doesn't need repeated resizing when adding.
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