Hi, I'm having problems trying to overload the post increment operator in C#. Using integers we get the following results.
int n;
n = 1;
Console.WriteLine(n++); // 1
Console.WriteLine(n); // 2
n = 1;
Console.WriteLine(++n); // 2
Console.WriteLine(n); // 2
But, when I try it using classes, it looks like the objects are exchanged.
class Account
{
public int Balance { get; set; }
public string Name { get; set; }
public Account(string name, int balance)
{
Balance = balance;
Name = name;
}
public override string ToString()
{
return Name + " " + Balance.ToString();
}
public static Account operator ++(Account a)
{
Account b = new Account("operator ++", a.Balance);
a.Balance += 1;
return b;
}
public static void Main()
{
Account a = new Account("original", 10);
Console.WriteLine(a); // "original 10"
Account b = a++;
Console.WriteLine(b); // "original 11", expected "operator ++ 10"
Console.WriteLine(a); // "operator ++ 10", expected "original 11"
}
}
Debugging the application, the operator overloaded method, returns the new object with the old value (10) and the object that has been passed by reference, has the new value (11), but finally the objects are exchanged. Why is this happening?