Postfix increment and decrement operators in CSharp

Postfix increment and decrement operators are great for doing quick addition and subtraction. Using your C# knowledge and not your compiler, what will the output be?

int i = 1;
string result = String.Format("{0},{1},{2}", i--, i++, i++);
Console.WriteLine(result);

Have your guess?

The output reads as follows. 1,0,1 and the last value of i is actually 2. Why is this?  We are using post operators, meaning, the compiler is going to read the value of i, then it will increment or decrement depending.  In the above example, the last i++ happens after the value of {2} is read, so it will not be seen as 2 in the console window and is not used in any execution path.  So let’s take a look at the opposite of above.

int i = 1;
string result = String.Format("{0},{1},{2}", --i, ++i, ++i);
Console.WriteLine(result);

Have your answer for this version?

The output ends up being 0,1,2 with a final value of i =2.  The reasoning is opposite of the above.  These operators will apply the increment or decrement prior to reading i.


Leave a Reply

Your email address will not be published. Required fields are marked *

StackOverflow Profile