Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array object[] in covariance behavior

Tags:

c#

covariance

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?

like image 897
Misters Avatar asked Dec 04 '25 23:12

Misters


1 Answers

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!
like image 55
Luaan Avatar answered Dec 06 '25 15:12

Luaan