Click here to Skip to main content
13,089,401 members (53,058 online)
Rate this:
Please Sign up or sign in to vote.
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
Posted 23-Feb-09 20:27pm

1 solution

Rate this: bad
Please Sign up or sign in to vote.

Solution 1

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;
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+ :)
  Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy |
Web04 | 2.8.170813.1 | Last Updated 18 Jul 2011
Copyright © CodeProject, 1999-2017
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100