0
  1. According to this question the default capacity set to new List<int>; is 0 and after Add(3); it's 4.
  2. The capacity set to new List<int>(5); should be 5 because the capacity is set via the parameter.
  3. However what's the capacity set to new List<int>() {3,5}; ? 4 or 2 ?
    1. It should be 4 if it behaves like in 1. above: the two initialization values in {3, 5} are added with two consecutive Add() operations so that the capacity is still 4 because the two values did not overflow this capacity.
    2. Or is it set to 2 by the Compiler because it recogizes the two values, 3 and 5 that are added to the List, counts them and sets this number as the capacity ?

This question matters in regards to the garbage collector performance as desribed in this blog.

Stonecrusher
  • 184
  • 1
  • 2
  • 14
  • 5
    Why not just try it out? It's 2 lines of code – UnholySheep Mar 30 '20 at 19:15
  • 1
    Also, as per the official docs(https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/object-and-collection-initializers#collection-initializers), collection initialization is just syntax sugar for `Add` calls – UnholySheep Mar 30 '20 at 19:17
  • 1
    In #3, `new List()` is the same as #1, then `{ 3, 5 }` calls `Add` twice. The first `(3)` increases the capacity to 4 (again same as #1), then the second `(5)` doesn't require more capacity so it doesn't change. That said, the capacity increase is an implementation detail. Don't rely on any specific increase in size or algorithm for determining how much to increase. (Finally, in #3.2, re *"by the Compiler"*, the compiler has no control over the object's implementation.) – madreflection Mar 30 '20 at 19:20

1 Answers1

0

This code new List<int>() {3,5}; is identical to

var list = new List<int>(); 
list.Add(3);
list.Add(5};

So the answer is 4.

C# compiler is smart but not that smart yet.

Optional Option
  • 1,521
  • 13
  • 33