In the book I’m reading _Pro C# 2008 and the .NET Platform” there is a chapter on CIL with some code that I am confused about.

Why is the step highlighted necessary? As I see it, this is what the code is doing.
- A local integer variable “i” is created and is initialized to 0 (by virtue of integers are always initialized to 0 if not explicitly assigned a value)
- (IL_0000) The value of the local variable [0] (which is “i”) is loaded onto the stack
- (IL_0001) Then the value is popped off the stack and assigned to “i” again . . . WHY? “i” is already 0!
From a memory standpoint, you could consider the initialization of i to 0 unnecessary, as the default value of an initialized int32 variable is 0.
However, the compiler is preserving the semantic information of the loop in the source code. The variable i is, after all, assigned to 0 in the for statement, and this information ends up serialized in the IL. It’s likely that this statement will be optimized away by the JIT anyway. At least Mono’s JIT does so. From the CIL standpoint it makes it easy to see what’s happening:
At the CIL level, a for is basically:
It’s quite easy to visually identify the different for elements in the CIL above.