I had a compile error while assinging int[] to object[] (the question is not mine).
The accepted answer states that that's because the array covariance (please read the question and the answer for the sake of better understanding).
Now my situation is that while I cannot assign int[] to object[] because int is value type (struct) I wonder why I can do this now:
var arrayOfObjects = new object[] { 58, 58, 78 };// it accepts values types as initializers!
Why does this work if I am initializing value types to the array object? Should not be reciprocal not accepting values types neither?
Because you're (implicitly) casting one item after another into object. You're not assigning a int[] array to a object[] variable - you're creating an object[] variable from individual int values (which get implicitly cast and boxed).
To show this without the array initializer:
object[] objarr = new object[1];
objarr[0] = 42; // Fine, translates basically into objarr[0] = (object)42;
int[] intarr = new int[1];
intarr[0] = 42; // Also fine
objarr = intarr; // No can do!
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