i++
will give you the original value, not the incremented, You will see the change on the next usage of i
. If you want to get the incremented value then use ++i
.
See the detailed answer by Eric Lippert on the same issue
Question
I tried to do the following
i=0;
if (i++ % Max_Col_items == 0 && i !=0)
{
}
and discovered that it increased i
in the middle
i % Max_Col_items == 0;
i=i+1;
i !=0;
when I though it would add increase i
in the end:
i % Max_Col_items == 0;
i !=0;
i=i+1;
Can any one find explanation of how i++
works in C#?
Solution
i++
will give you the original value, not the incremented, You will see the change on the next usage of i
. If you want to get the incremented value then use ++i
.
See the detailed answer by Eric Lippert on the same issue
OTHER TIPS
i++
immediately increments the value of i
but evaluates as the value before incrementation.
It doesn't leave the value of i
untouched until the end of the line of code, which appears to be what you expect.
That is because (as you have rightly noted)
i % Max_Col_items == 0;
is an operation in itself. Once that line of operation is over (with value of i ) the increment is done.