Question

I have an Ascii class to help me manage and string with char limits, and i want to be able to increment it like a char, so I have some operator overloads. Given the following code:

 public static AsciiWord operator++(AsciiWord aWord){
        aWord.numValue++;
        return aWord.Copy();
    }

Do I really need the copy?

Note: Copy is a extension method I copied off of SO that performs a deep copy of just about anything.

Was it helpful?

Solution

The increment operator is supposed to leave the original value unchanged, and return an incremented copy of it. However, in your implementation, you're mutating the aWord passed in as an argument.

E.g., the following code uses the post-fix increment operator and expects oldValue.NumValue to be 0, but with your current implementation it will be 1.

AsciiWord aWord = new AsciiWord { NumValue = 0 };
AsciiWord oldValue = aWord++;
Assert.Equal(0, oldValue.NumValue); // fails

int i = 0;
int oldIntValue = i++;
Assert.Equal(0, oldIntValue); //passes

In other words - AsciiWord should be deeply immutable.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top