Search code examples
c#arrayscollection-initializer

System.Array does not support Add(), so how does collection initializer work?


In C# you can initialize an array like so:

var example = new int[] { 1, 4, 3 };

As quoted in Custom Collection Initializers:

The collection object to which a collection initializer is applied must be of a type that implements System.Collections.IEnumerable or a compile-time error occurs. For each specified element in order, the collection initializer invokes an Add method on the target object with the expression list of the element initializer as argument list, applying normal overload resolution for each invocation. Thus, the collection object must contain an applicable Add method for each element initializer.

But you cannot Add to a System.Array, one has to create a new larger Array for each added item, that is not good for performance. So how does C# work when using a collection initializer on an Array? I wonder if I could write a class with an internal Array that supports a collection initializer.


Solution

  • Array isn't a custom collection. It's an array. array initializers pre-date collection initializers, and were what inspired the syntax.