I have some code
static void Main(string[] args)
{
int j = 0;
for (int i = 0; i < 10; i++)
j = j++;
Console.WriteLine(j);
}
Why answer is 0 ?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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 :)):
Since it is a value object, the two objects (
jandintermediateValue) 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.
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.
Back to the original point, though 🙂
If you do the following, then you will get the expected result.
This is because the increment occurs first, then the assignment.
However, ++ can be used on its own. So, I would just rewrite this as
As it simply translates into