[Solved] What is the difference between these two list declarations?


The first declaration creates a list with an underlying array with a size of 5.

The second declaration copies data from the passed array to the underlying array in the list.

So the second declaration needs to:

  • Create an empty array
  • Copy the values in that array to another array

Since it’s also harder to read (what’s the point of passing an empty array to a list constructor?), there really isn’t any reason at all to use the second instead of the first.

The reason the overload is there is to allow you to prefill the list with values from another array or enumerable. For example:

var list = new List<int>(Enumerable.Range(1, 100));

(though of course, even then you’d usually use Enumerable.Range(1, 100).ToList() instead :))

5

solved What is the difference between these two list declarations?