0

I am new to c#. I am currently follow some tutorials and try to learn how to read the intermediate language (IL) with ildasm.exe.

I wrote this short code in c#:

using System;

namespace MainApp
{
    class App
    {
        public static void Main()
        {
            int[] array1D = new int[4];
            int len = array1D.GetLength(0);
            //Console.WriteLine(array1D[1]);
        }
    }
}

Then, I compiled the code and got this il-code:

.method public hidebysig static void  Main() cil managed
{
  .entrypoint
  // Code size       17 (0x11)
  .maxstack  2
  .locals init (int32[] V_0,
           int32 V_1)
  IL_0000:  nop
  IL_0001:  ldc.i4.4
  IL_0002:  newarr     [System.Runtime]System.Int32
  IL_0007:  stloc.0
  IL_0008:  ldloc.0
  IL_0009:  ldc.i4.0
  IL_000a:  callvirt   instance int32 [System.Runtime]System.Array::GetLength(int32)
  IL_000f:  stloc.1
  IL_0010:  ret
} // end of method App::Main

My question: What the point of line 7 and 8?

Guru Stron
  • 102,774
  • 10
  • 95
  • 132
Skobo Do
  • 49
  • 6
  • 1
    It is pushing a value onto the stack in preparation of the call. Parameter for the call have to be on the stack. The parameters for the call are after the stack pointer. Doing a store and load is simplest method for putting an item on the stack. – jdweng Jul 12 '23 at 13:46
  • 2
    maybe it helps https://stackoverflow.com/questions/44733675/why-there-is-a-ldloc-0-just-after-stloc-0-in-il-code – DonMiguelSanchez Jul 12 '23 at 13:48
  • 3
    It seems to be a Debug build. In Release they should go away, along with `nop`. – György Kőszeg Jul 12 '23 at 13:48
  • By *"line 7 and 8"*, do you mean *labels* `IL_0007` and `IL_0008` ? – madreflection Jul 12 '23 at 15:02
  • 1
    Contrary to what jdweng's comment suggests, the "stack" in this case is not the memory buffer traversed by the stack pointer. Rather, it's the *evaluation stack*. IL is a stack-based language. Every instruction operates on the evaluation stack in some way, pushing values, popping values, or both (or neither in the case of `nop`). Whether arguments are passed on the stack, in registers, a combination of those, or some other way altogether, is up to the JIT compiler. – madreflection Jul 12 '23 at 15:10
  • 1
    As you read the documentation for instructions (like [stloc.0](https://learn.microsoft.com/en-us/dotnet/api/system.reflection.emit.opcodes.stloc_0)), pay attention to the "stack transitional behavior". This indicates how the evaluation stack is affected by the operation. At the beginning of a method, the evaluation stack is empty, and it must be empty by the end or it's an "invalid program". – madreflection Jul 12 '23 at 15:16

0 Answers0