Search code examples
c#if-statementdefinitionintermediate-language

What does an if look like in IL?


What does an if statement look like when it's compiled into IL?

It's a very simple construct in C#. Can sombody give me a more abstract definition of what it really is?


Solution

  • Here are a few if statements and how they translate to IL:

    ldc.i4.s 0x2f                      var i = 47;
    stloc.0 
    
    ldloc.0                            if (i == 47)
    ldc.i4.s 0x2f
    bne.un.s L_0012
    
    ldstr "forty-seven!"                   Console.WriteLine("forty-seven!");
    call Console::WriteLine
    
    L_0012:
    ldloc.0                            if (i > 0)
    ldc.i4.0 
    ble.s L_0020
    
    ldstr "greater than zero!"             Console.WriteLine("greater than zero!");
    call Console::WriteLine
    
    L_0020:
    ldloc.0                            bool b = (i != 0);
    ldc.i4.0 
    ceq 
    ldc.i4.0 
    ceq 
    stloc.1 
    
    ldloc.1                            if (b)
    brfalse.s L_0035
    
    ldstr "boolean true!"                  Console.WriteLine("boolean true!");
    call Console::WriteLine
    
    L_0035:
    ret
    

    One thing to note here: The IL instructions are always the “opposite”. if (i > 0) translates to something that effectively means “if i <= 0, then jump over the body of the if block”.