3

There is a difference between h = ++i and h = i++ in C#. So what I need is a way to declare different overloaded operators for pre-increment (i.e. ++i) and post-increment (i++) in C#. How would I do that please?

I am aware of the fact that both operators do the same to the value they work on - the problem is the point of time when the assignment is done. I know how to do it in C++, but that is not the question. I am wondering whether there is a way to overload both ways this operator can behave in C#, and if so, how to do it.

Razzupaltuff
  • 2,250
  • 2
  • 21
  • 37

2 Answers2

4

You can't http://msdn.microsoft.com/en-us/library/36x43w8w(v=vs.71).aspx. You can only overload ++, the only difference is when your overload will be called.

Edit: Also, you can only overload ++ for user-defined types, so it's basically just becoming an alias for a function of your choice.

anthonyvd
  • 7,329
  • 4
  • 30
  • 51
2

There is no difference in decleration of those operators. Infact, they act exactly the same, the only difference is the returned value. The ++ operator overload works for both, the different return value is supplied by the runtime, not the user code.

Edit: found it What is the difference between i++ and ++i?

Community
  • 1
  • 1
Femaref
  • 60,705
  • 7
  • 138
  • 176
  • The return value is not returned by the run time. "h = ++i;" is equivalent to "i = i + 1, h = i"; "h = i++;" is equivalent to "h = i; i = i + 1;". That's a matter of the semantics the parser detects and the code that is subsequently generated. – Razzupaltuff Apr 05 '11 at 14:00
  • I found the post. I have the feeling that the operators don't work the way you think they do in C#. – Femaref Apr 05 '11 at 14:06
  • I'd phrase your answer a bit differently. The short short version of Eric's answer to the other question is that the operators do the exact same steps in the exact same order, with the difference being the prefix form returns the new value (of `i` in this case), whereas the postfix returns the temporary copy of the old value. – Anthony Pegram Apr 05 '11 at 14:11
  • feel free to make adjustments. – Femaref Apr 05 '11 at 14:14