Why are implicit property names not allowed in an array of anonymous types?

You will either need to specify the names of the properties in your anonymous types implicitly, or use an array of object

var array = new[] { new { val1= A, val2=B }, new { val1=X, val2=Y } };

or

var array = new object [] { new { A, B }, new { X, Y } };

However lets take this a step further and use Tuples yehaa, shorter syntax, typed, and more succinct

var array = new[] { (A, B), (X, Y) };

or named tuples, best of all worlds

var array = new (int something ,int another)[] { (A, B), (X, Y) };

You can do this, although I don't know that you should.

int A = 5, B = 10, X = 5, Y = 5;
var array = new object[] { new { A, B }, new { X, Y } };

This is valid, and will compile just fine, and be very, very difficult to use. I strongly recommend against doing this.

As for the reason why using the implicit initialization syntax doesn't work, 12.6 of the spec has this to say about array initializers:

For a single-dimensional array, the array initializer must consist of a sequence of expressions that are assignment compatible with the element type of the array. The expressions initialize array elements in increasing order, starting with the element at index zero.

(emphasis mine)

So there isn't a compatible type between your two anonymous types as, well, they are anonymous.


Or one more case (in addition to the other answers):

int A = 5, B = 10, X = 5, Y = 5;
var array = new[] { new { A, B }, new { A=X, B=Y } };

In this case you are creating an array of implicitly typed object, each of which has two integer properties, one named A, the other named B.