Array object [] in covariance behavior

I had a compile error when defining int[]

beforeobject[]

(not mine).

The accepted answer says this is because array covariance (please read the question and answer for a better understanding).

Now my situation is that although I cannot assign int[]

to object[]

because int

- value type ( struct

), I am wondering 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 initialize value types for an array object? Shouldn't it be mutually not to take values โ€‹โ€‹of types not?

+3


source to share


3 answers


Because you are (implicitly) casting one element after another into object

. You are not assigning an array to a int[]

variable object[]

- you are creating a variable object[]

from individual values int

(which are implicitly displayed and put in boxes).

To show this without an 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!

      

+7


source


Here you are not building int[]

, integers are being put into objects, and instead you are creating object[]

. You can use other things as well:



var arrayOfObjects = new object[] { true, "false", 1, 10, new StringBuilder() }

      

+2


source


To complete the compiler's point of view, make the following statement:

void Main()
{
    object[] or = new object[] { 1, 2 };
}

      

This is the IL emitted by the compiler:

IL_0001:  ldc.i4.2    
IL_0002:  newarr      System.Object
IL_0007:  stloc.1     // System.Object[]
IL_0008:  ldloc.1     // System.Object[]
IL_0009:  ldc.i4.0    
IL_000A:  ldc.i4.1    
IL_000B:  box         System.Int32
IL_0010:  stelem.ref  
IL_0011:  ldloc.1     // System.Object[]
IL_0012:  ldc.i4.1    
IL_0013:  ldc.i4.2    
IL_0014:  box         System.Int32
IL_0019:  stelem.ref  
IL_001A:  ldloc.1     // System.Object[]
IL_001B:  stloc.0     // or
IL_001C:  ret      

      

The compiler takes values โ€‹โ€‹as to whether the operation does box

value type ( int

) and then calls stelem.ref

, which replaces the value of the element at the supplied index in the one-dimensional array with the ref (type O) pushed onto the stack.

+1


source







All Articles