When using the collection initializers in C# 3.0, is the initial capacity of the collection inferred from the number of elements used to initialize the collection? For example, is
List<int> digits = new List<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
equivalent to
List<int> digits = new List<int>(10) { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
No.
List<int> digits = new List<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
is equivalent to
List<int> temp = new List<int>();
temp.Add(0);
temp.Add(1);
temp.Add(2);
temp.Add(3);
temp.Add(4);
temp.Add(5);
temp.Add(6);
temp.Add(7);
temp.Add(8);
temp.Add(9);
List<int> digits = temp;
The number of items being added doesn't automatically change the initial capacity. If you're adding more than 16 items through the collection initializer you can combine the constructor and initializer like this:
List<int> digits = new List<int>(32) { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31 };
No, it's equivalent to:
// Note the () after <int> - we're calling the parameterless constructor
List<int> digits = new List<int>() { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
In other words, the C# compiler doesn't know or care what the parameterless constructor will do - but that's what it will call. It's up to the collection itself to decide what its initial capacity is (if it even has such a concept - a linked list doesn't, for example).
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