Click here to Skip to main content
15,901,205 members
Please Sign up or sign in to vote.
4.62/5 (9 votes)
See more:
I was just working on overloading the increment operator. I was hoping to have both pre-increment and post-increment. Unfortunately I see that the same method is called regardless of whether the operator is in pre- or post-position. So I checked the spec and was surprised to find:

Note that the operator returns the value produced by adding 1 to the operand, just like the postfix increment and decrement operators (§7.5.9), and the prefix increment and decrement operators (§7.6.5). Unlike in C++, this method need not, and, in fact, must not, modify the value of its operand directly.

What the heck good is an increment operator that doesn't increment?! If I want to do x += 1 I have the addition operator for that and it works just fine. I want x++ and ++x just like with the built-in numeric types; x = x++ or x = ++x would be ridiculous, but it appears that's all we're allowed.

Am I missing something? Does anyone have a work-around?

P.S. Or is just that it's 00:34 and I should go get some sleep? It seems to be working as expected somehow? [confused]

modified on Tuesday, February 24, 2009 2:33 AM

1 solution

When calling the increment operator, the object is assigned a new reference, that reference has the new values.

Example. We have a class IntWrapper
public class IntWrapper
    public int IntValue

and we want to use it like this
IntWrapper a = new IntWrapper();
IntWrapper b = a;
Console.WriteLine("a = {0}, b = {1}", a.IntValue, b.IntValue);

Here are two possible implementations for the increment operator overload in our class, the second is the correct way
public static IntWrapper operator ++(IntWrapper instance)
    // WRONG! a and b will be incremented
    return instance;

public static IntWrapper operator ++(IntWrapper instance)
    // CORRECT! Only a will be incremented
    IntWrapper result = new IntWrapper();
    result.IntValue = instance.IntValue + 1;
    return result;
Share this answer
Philippe Mori 18-Jul-11 22:07pm    
Fixed formatting by replacing <br> tag by new line in <pre> blocks.
VJ Reddy 1-Jun-12 19:48pm    
Good answer. 5!
Linto Leo Tom 2-Jun-12 12:07pm    
Great stuff 5+ :)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900