Alex Rivera | Logout

What does "count++" return in C#?

Asked 2011-02-17T15:05:09.637
18

Just ran into a bit of code that wasn't doing what I thought it should. Do other people think this should return 1? Is there a good explanation as to why it doesn't??

int count = 0;

count++.ToString(); // Returns 1 no?

I always thought count++ was the same as count = count + 1...

c#
Edit
Report

2 Answers

2
(++i).ToString();

does exactly what you expect.

answered 2011-02-17T15:07:00.470
1

Your original code will always show 0.

Try this:

(++c).ToString();

This will return 1.

From the MSDN site:

The first form is a prefix increment operation. The result of the operation is the value of the operand after it has been incremented.

The second form is a postfix increment operation. The result of the operation is the value of the operand before it has been incremented.

answered 2011-02-17T15:07:55.550

Your Answer