I\'m having problems trying to overload the post increment operator in C#. Using integers we get the following results.
int n;
n = 10;
Console.WriteLine(n);
The key is in understanding how the line Account b = a++; works. Given how your code is written, this line is the equivalent of this:
Account b = a;
a++;
And that is the order it will execute in. The assignment effectively(1) happens before the increment. So, the first effect of this line is that a and b both refer to the original object a.
Now the ++ portion will be evaluated. Inside of the operator method, we increment the Balance of the original object. At this point a and b are both pointing at the original, with a Balance of 11, and b will continue to do so.
However, you've created a new object inside the operator method and returned it as the output of the operator. a will now be updated to point at the newly created object.
So, a now points to a new object, while b continues to point to the original. That's why the WriteLine output appears swapped.
As @MarkusQ pointed out, the ++ operator is meant to do in-place modification. By generating a new object, you're breaking that assumption. Operator overloading on objects is a tricky subject, and this is an excellent example of why it's better avoided in most cases.
1 - Just for accuracy's sake, the assignment does not actually happen before the increment when dealing with operators on objects, but the end result is the same in this case. Actually, the original object reference is copied, the operation is carried out on the original, and then the copied reference is assigned to the left-hand variable. It's just easier to explain if you pretend that assignment happens first.
What's really happening is that this:
Account b = a++;
results in this, due to how the ++ operator works on objects:
Account copy = a;
Account x = new Account("operator ++", a.Balance);
a.Balance += 1; // original object's Balance is incremented
a = x; // a now points to the new object, copy still points to the original
Account b = copy; // b and copy now point at the same, original, object