The value of the post-increment (postfix) ++
operator is the value of the operand before it is incremented. So if the current value is 2
, the operator saves 2
, increments it to 3
but returns the saved value.
For your function
public static int IncrementByOne(int number)
{
return number++;
}
Look at the generated IL code to see what happens:
IncrementByOne:
IL_0000: ldarg.0 // load 'number' onto stack
IL_0001: dup // copy number - this is the reason for the
// postfix ++ behavior
IL_0002: ldc.i4.1 // load '1' onto stack
IL_0003: add // add the values on top of stack (number+1)
IL_0004: starg.s 00 // remove result from stack and put
// back into 'number'
IL_0006: ret // return top of stack (which is
// original value of `number`)
The reason the postfix ++
operator returns the original (not the incremented) value is because of the dup
statement - the value of number
is on the stack twice and one of those copies stays on the stack by the ret
statment at the end of the function so it gets returned. The result of the increment goes back into number
.