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 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With