开发者

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

Just ran into a bit of code that wasn't doing what I thou开发者_StackOverflowght 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...


x++ is a post increment operator. It means that the value of x is incremented, but the old (non-incremented) value of x is returned (0 in your case, to which ToString is applied).

To get the behavior you want, use the pre increment operator ++x.


At least four of the answers posted so far are wrong. It is an extremely common error to believe that the ++ operator has the same ill-defined semantics as it does in C. It does not. The semantics of the ++ operator are well-defined, and are quite different from how they have been described by the incorrect answers here. See my answer to the last time this question was asked for details:

What is the difference between i++ and ++i?


x++ is post increment; the current value (0) is used as the result, then the ++ happens.

A bit like:

var tmp = count;
count++;
Consle.WriteLine(tmp);

The pre-increment (++x) would behave as you expected.


(++i).ToString();

does exactly what you expect.


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.


No, ++count return "1". count++.ToString() execute the ToString() method and then increments count, so it returns "0".

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜