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

  • A+

Why isn't this allowed?

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

When I try to compile, I get:

CS0826: No best type found for implicitly-typed array

Feels a bit counter-intuitive, because with a regular anonymous type I can do this:

int X = 5, Y = 5; var point = new { 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.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: