HKstrongside
HKstrongside

Reputation: 343

Differences between these two List<char> initializations in C#

I am going through some C# training and am trying to understand the difference between these two List<char> initializations. I have not had much luck finding a good explanation.

When I debug, both show a count of 5. The first shows a capacity of 5 but the second shows a capacity of 8? When I look at Raw View > Non-public-members > _items, the extra [5],[6],[7] show a value of 0,'\0'

I would really appreciate some help understanding the differences and why/when I should use each one. Thanks in advance.

var vowels1 = new List<char>(new char[] {'a', 'e', 'o', 'u', 'i'});

var vowels2 = new List<char>(){'a', 'e', 'o', 'u', 'i'};

Upvotes: 1

Views: 105

Answers (2)

Rich O&#39;Kelly
Rich O&#39;Kelly

Reputation: 41757

The first passes the array the list uses as its backing store. Hence the capacity of 5.

The second is syntantic sugar for instantiate using the parameterless constructor, then call a method called add with each element (called a collection initialiser). IIRC the initial capacity set when the default constructor used is 4, which subsequently doubles to size 8 when the 5th element is added.

Upvotes: 2

Selman Gen&#231;
Selman Gen&#231;

Reputation: 101681

The second code uses collection initializer, it is equivalent to this:

var vowels2 = new List<char>();
vowels2.Add('a');
vowels2.Add('e');
...

The capacity value is managed internally in the list and it is being increased when needed. In the first code you are giving constructor an array so the length is known and the capacity is set to 5. In the second code the items are added one by one and the capacity is increased based on that, so that's why it's different.

The extra items u see is the items of the internal array in the List<T> class which are initialized the default values. When you have an array of structs (char is a struct) all values are initialized to defaults, for example if u create an array of 10 ints they will be initialized to 0. It's the same for char, just the default value is \0.

At the end both code does the same thing, your list does not have any extra items. The ones you are seeing in the debugger are implementation details.

Upvotes: 3

Related Questions