Why is there no difference in ++ foo and foo ++ when the ++ operator is overloaded?

Possible duplicate:
Operator overload with subsequent increase
Why are Postfix ++ / - classified as primary operators in C #?

I saw that I can overload the ++ and -- operators. You usually use these operators in two ways. Pre and post increment / deccrement 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 slightly different with 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 last two lines output the same thing? And more specifically, why does the first line (of two) print flying ?


Decisions should change the operator overload to:

  public static Fly operator ++(Fly fly) { Fly result = new Fly {Status = "flying"}; return result; } 
+4
source share
1 answer

The difference between prefix and postfix ++ is that the foo++ value is the foo value before calling the ++ operator, while ++foo is the value returned by the ++ operator. In your example, these two values ​​are the same, since the ++ operator returns the original fly link. If instead he returned a new β€œflying” Summer, then you will see the difference that you expect.

+4
source

Source: https://habr.com/ru/post/1445820/


All Articles