Is initial capacity possible with collection initializers?

When using collection initializers in C # 3.0, is the initial collection capacity obtained from the number of elements used to initialize the collection? For instance,

List<int> digits = new List<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; 

equivalently

 List<int> digits = new List<int>(10) { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; 
+4
source share
2 answers

Not.

 List<int> digits = new List<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; 

equivalently

 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 added items does not automatically change the initial capacity. If you add more than 16 elements through the collection initializer, you can combine the constructor and initializer as follows:

 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 }; 
+4
source

No, this is 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 does not know and does not care about what the constructor will do without parameters - but what it will call. It depends on the collection itself to decide what its initial capacity is (if it even has such a concept - a linked list, for example).

+4
source

Source: https://habr.com/ru/post/1299554/


All Articles