Explaining post-increment in C# [duplicate]

断了今生、忘了曾经 提交于 2019-12-01 14:18:54

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;

As the name says, post-increment increments after the value has been used

y = x++;

According to the C# Language Specification this is equivalent to

temp = x;
x = x + 1;
y = temp;

Applied to your original problem it means that j remains the same after these operations.

temp = j;
j = j + 1;
j = temp;

You can also use pre-increment, which does the opposite

x = x + 1;
y = x;

or

y = ++x;

See Postfix increment and decrement operators on MSDN

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!