Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 };
like image 219
DumbCode Avatar asked Feb 06 '19 23:02

DumbCode


3 Answers

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) };
like image 63
TheGeneral Avatar answered Oct 21 '22 03:10

TheGeneral


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.

like image 6
Jonathon Chase Avatar answered Oct 21 '22 05:10

Jonathon Chase


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.

like image 3
Flydog57 Avatar answered Oct 21 '22 03:10

Flydog57