Possible Duplicate:
Post-increment Operator Overloading
Why are Postfix ++/— categorized as primary Operators in C#?
I saw that I can overload the ++ and -- operators.
Usually you use these operators by 2 ways. Pre and post increment/deccrement an int
Example:
int b = 2;
//if i write this
Console.WriteLine(++b); //it outputs 3
//or if i write this
Console.WriteLine(b++); //outpusts 2
But the situation is a bit different when it comes to operator overloading:
class Fly
{
private string Status { get; set; }
public Fly()
{
Status = "landed";
}
public override string ToString()
{
return "This fly is " + Status;
}
public static Fly operator ++(Fly fly)
{
fly.Status = "flying";
return fly;
}
}
static void Main(string[] args)
{
Fly foo = new Fly();
Console.WriteLine(foo++); //outputs flying and should be landed
//why do these 2 output the same?
Console.WriteLine(++foo); //outputs flying
}
My question is why do these two last lines output the same thing? And more specifically why does the first line(of the two) output flying?
Solutions is to change the operator overload to:
public static Fly operator ++(Fly fly)
{
Fly result = new Fly {Status = "flying"};
return result;
}