Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the .Count of a List<T>(Int32) with initial size 0?

Tags:

c#

list

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!

like image 334
Julian Avatar asked Dec 03 '22 15:12

Julian


1 Answers

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.

like image 155
Martheen Avatar answered Dec 24 '22 13:12

Martheen