Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the initial capacity inferred when using collection initializers?

Tags:

c#

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 };
like image 892
Jamie Ide Avatar asked Feb 28 '23 17:02

Jamie Ide


2 Answers

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 };
like image 85
Samuel Neff Avatar answered Apr 28 '23 21:04

Samuel Neff


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).

like image 28
Jon Skeet Avatar answered Apr 28 '23 22:04

Jon Skeet