public static MyClass operator++(MyClass op)
{
MyClass result = new MyClass(); // MyClass() x=y=z=0;
result.x = op.x + 1;
result.y = op.y + 1;
result.z = op.z + 1;
return result:
}
//...
public void Main()
{
MyClass c = new MyClass();
MyClass b = new MyClass(1,2,3); //ctor x = 1, ...
c = b++;
}
The question is why variable b going to change?
because result.x = op.x + 1; shouldn’t change op.x
result actually is c is (1,2,3) b is (2,3,4)
I don’t understand why not c is (2,3,4) and b is (1,2,3)
You say, “because
result.x = op.x + 1shouldn’t change op.x.” But++is not the same as+ 1. It is the standard postfix increment operator which increments the operandbby using your custom overload — it assigns the new value tobimmediately after passing the previous value toc. If it were the prefix operator (++b), it would have incremented before passing the value toc.Without any overloads at all, the code:
Is equivalent to:
And
Is equivalent to:
Now using your overload, it’s more equivalent to: