0

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.

Community
  • 1
  • 1

2 Answers2

5

Quote you've provided is related to Custom collections.

But array is not a custom collection, it is builtin type and have its own specification of initializer syntax available here. In particular, that specification doesn't require any Add method.

Andrey Korneyev
  • 26,353
  • 15
  • 70
  • 71
2

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

Damien_The_Unbeliever
  • 234,701
  • 27
  • 340
  • 448
  • The link from Any Korneyev is good. But I prefer this answer because I didn't know array initializers are older and distinct from collection initializers. – Stefan Wilms Jan 28 '16 at 11:17