Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CIL OpCode (Ldarg_0) is used even though there are no arguments

Tags:

c#

clr

cil

il

I have the following C# code.

public void HelloWorld()
{
    Add(2, 2);
}

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

It produces the following 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 the line at offset 0001:

ldarg.0

I know what that opcode is for, but I don't really understand why it's being used in this method, as there are no arguments, right?

Does someone know why? :)

like image 734
animaonline Avatar asked May 02 '13 19:05

animaonline


3 Answers

I think that the ldarg.0 is loading this onto the stack. See this answer MSIL Question (Basic)

like image 80
Twiltie Avatar answered Sep 18 '22 14:09

Twiltie


The line at offset 0001: Loads the argument at index 0 onto the evaluation stack.

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

The argument at index 0 is the instance of the class that contains the methods HelloWorld and Add, as this (or self in other 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 as call: this.Add(2,2); in C#.

like image 32
Juan Rey Hernández Avatar answered Sep 22 '22 14:09

Juan Rey Hernández


In instance methods there is an implicit argument with index 0, representing the instance on which the method is invoked. It can be loaded on the IL evaluation stack using ldarg.0 opcode.

like image 31
Zakharia Stanley Avatar answered Sep 21 '22 14:09

Zakharia Stanley