Free mag vol1 | Page 735

CHAPTER 18  UNDERSTANDING CIL AND THE ROLE OF DYNAMIC ASSEMBLIES ldarg.2 ... } // Load "b" onto the stack. Representing Iteration Constructs in CIL Iteration constructs in the C# programming language are represented using the for, foreach, while, and do keywords, each of which has a specific representation in CIL. Consider the following classic for loop: public static void CountToTen() { for(int i = 0; i < 10; i++) ; } Now, as you may recall, the br opcodes (br, blt, and so on) are used to control a break in flow when some condition has been met. In this example, you have set up a condition in which the for loop should break out of its cycle when the local variable i is equal to or greater than the value of 10. With each pass, the value of 1 is added to i, at which point the test condition is yet again evaluated. Also recall that when you make use of any of the CIL branching opcodes, you will need to define a specific code label (or two) that marks the location to jump to when the condition is indeed true. Given these points, ponder the following (augmented) CIL code generated via ildasm.exe (including the autogenerated code labels): .method public hidebysig static void CountToTen() cil managed { .maxstack 2 .locals init ([0] int32 i) // Init the local integer "i". IL_0000: ldc.i4.0 // Load this value onto the stack. IL_0001: stloc.0 // Store this value at index "0". IL_0002: br.s IL_0008 // Jump to IL_0008. IL_0004: ldloc.0 // Load value of variable at index 0. IL_0005: ldc.i4.1 // Load the value "1" on the stack. IL_0006: add // Add current value on the stack at index 0. IL_0007: stloc.0 IL_0008: ldloc.0 // Load value at index "0". IL_0009: ldc.i4.s 10 // Load value of "10" onto the stack. IL_000b: blt.s IL_0004 // Less than? If so, jump back to IL_0004 IL_000d: ret } In a nutshell, this CIL code begins by defining the local int32 and loading it onto the stack. At this point, you jump back and forth between code label IL_0008 and IL_0004, each time bumping the value of i by 1 and testing to see whether i is still less than the value 10. If so, you exit the method.  Source Code The CilTypes example is included under the Chapter 18 subdirectory. 678