Search code examples
cilboxing

CIL / MSIL Boxing issue?


I thought I knew how boxing and unboxing works, but apparently I don't, because what I would expect to compile properly,

// the start of my Program::Main()
.maxstack 8 // Yes I know it's a large stack size for
            // the given method; it's just a test program ;)
.entrypoint
ldc.i4  10
box     int32
unbox   int32 // Removing these two lines
box     int32 // makes it run properly
call    void [mscorlib]System.Console::WriteLine(object)
ret

instead throws an error saying "Invalid IL code in Program:Main(): box 0x1b000004."

From my understanding, the operations went like this:

// instruction:        stack after instruction is run:
   ldc.i4 10        // 10
   box int32        // object(int32,10)
   unbox int32      // 10
   box int32        // should be object(int32,10), but instead, got an error.

I tried removing the unboxing and re-boxing, and it runs fine. Also, removing the call to WriteLine and the second boxing, just leaving an int, then discarding the int from the stack runs fine. For some strange reason, boxing, unboxing, then reboxing throws an error.

So, what's different during the second boxing that causes it to throw an error instead of executing like the first?


Solution

  • unbox pushes a managed pointer to the value onto the evaluation stack, not the value itself. Try using unbox.any instead. – Lee