CIL OpCode (Ldarg_0) is used, although no arguments

I have the following C # code.

public void HelloWorld() { Add(2, 2); } public void Add(int a, int b) { //Do something } 

He produces the next CIL

 .method public hidebysig instance void HelloWorld() cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: ldc.i4.2 IL_0003: ldc.i4.2 IL_0004: call instance void ConsoleApplication3.Program::Add(int32, int32) IL_0009: nop IL_000a: ret } // end of method Program::HelloWorld 

Now, what I don't understand is a line at offset 0001:

ldarg.0

I know what this operation code is for, but I don’t understand why it is used in this method, since there are no arguments, right?

Does anyone know why? :)

+7
source share
3 answers

Instance methods have an implicit argument with index 0 representing the instance on which the method is invoked. It can be loaded ldarg.0 IL evaluation stack using the ldarg.0 code.

+19
source

I think ldarg.0 loads this on the stack. See This Answer. MSIL Question (Basic)

+10
source

Line offset 0001: Loads an argument with index 0 on the evaluation stack.

See also at: http://msdn.microsoft.com/en-us/library/system.reflection.emit.opcodes.ldarg_0.aspx

The argument at index 0 is an instance class that contains the HelloWorld and Add methods, since this (or the "me" in another languajes)

  IL_0001: ldarg.0 //Loads the argument at index 0 onto the evaluation stack. IL_0002: ldc.i4.2 //Pushes a value 2 of type int32 onto the evaluation stack. IL_0003: ldc.i4.2 //Pushes a value 2 of type int32 onto the evaluation stack. IL_0004: call instance void ConsoleApplication3.Program::Add(int32, int32) 

... this last line is a call: this.Add(2,2); in c #.

+1
source

All Articles