Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C#
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
good
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
    {
        get;
        set;
    }
}
and we want to use it like this
IntWrapper a = new IntWrapper();
IntWrapper b = a;
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
    instance.IntValue++;
    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;
}
  Permalink  
v2
Comments
Philippe Mori at 18-Jul-11 22:07pm
   
Fixed formatting by replacing <br> tag by new line in <pre> blocks.
VJ Reddy at 1-Jun-12 19:48pm
   
Good answer. 5!
Linto Leo Tom at 2-Jun-12 12:07pm
   
Great stuff 5+ :)
  Print Answers RSS
0 Sergey Alexandrovich Kryukov 528
1 OriginalGriff 459
2 ChintanShukla 305
3 Richard Deeming 275
4 RyanDev 230
0 Sergey Alexandrovich Kryukov 8,858
1 OriginalGriff 7,451
2 CPallini 2,603
3 Richard MacCutchan 2,095
4 Abhinav S 1,893


Advertise | Privacy | Mobile
Web02 | 2.8.140827.1 | Last Updated 18 Jul 2011
Copyright © CodeProject, 1999-2014
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