This is the intermediate language (IL) that the compiler generates (VS2013RC/.NET 4.5.1RC):
.method public hidebysig static int32 GetNextIndex() cil managed
{
.maxstack 8
L_0000: ldsfld int32 ConsoleApplication4.Program::index
L_0005: dup
L_0006: ldc.i4.1
L_0007: add
L_0008: stsfld int32 ConsoleApplication4.Program::index
L_000d: ret
}
So, what does that do? Let's say that index
has the value 6 before calling it.
L_0000: ldsfld int32 ConsoleApplication4.Program::index
loads the value of index
onto the evaluation stack - stack contains 6
.
L_0005: dup
duplicates the value on the top of the stack - stack contains 6, 6
L_0006: ldc.i4.1
loads the value 1
onto the stack - stack contains 6, 6, 1
L_0007: add
adds the top two values on the stack, and places the result back on the stack. stack contains 6, 7
L_0008: stsfld int32 ConsoleApplication4.Program::index
Stores the top value on the stack into index
. index
now equals 7
, stack contains 6
.
L_000d: ret
Takes the top value on the stack (6
) as the return value.