This is because of the way the ++ increment works. The order of operations is explained in this MSDN article This can be seen here (somebody please correct me if I am reading the spec on this one wrong :)):
int j = 2;
//Since these are value objects, these are two totally different objects now
int intermediateValue = j;
j = 2 + 1
//j is 3 at this point
j = intermediateValue;
//However j = 2 in the end
Since it is a value object, the two objects (j
and intermediateValue
) at that point are different. The old j was incremented, but because you used the same variable name, it is lost to you. I would suggest reading up on the difference of value objects versus reference objects, also.
If you had used a separate name for the variable, then you would be able to see this breakdown better.
int j = 0;
int y = j++;
Console.WriteLine(j);
Console.WriteLine(y);
//Output is
// 1
// 0
If this were a reference object with a similar operator, then this would most likely work as expected. Especially pointing out how only a new pointer to the same reference is created.
public class ReferenceTest
{
public int j;
}
ReferenceTest test = new ReferenceTest();
test.j = 0;
ReferenceTest test2 = test;
//test2 and test both point to the same memory location
//thus everything within them is really one and the same
test2.j++;
Console.WriteLine(test.j);
//Output: 1
Back to the original point, though :)
If you do the following, then you will get the expected result.
j = ++j;
This is because the increment occurs first, then the assignment.
However, ++ can be used on its own. So, I would just rewrite this as
j++;
As it simply translates into
j = j + 1;