Search code examples
c#operator-overloadingincrementpost-incrementpre-increment

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


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;
        }

Solution

  • The difference between prefix and postfix ++ is that the value of foo++ is the value of foo before calling the ++ operator, whereas ++foo is the value that the ++ operator returned. In your example these two values are the same since the ++ operator returns the original fly reference. If instead it returned a new "flying" Fly then you would see the difference you expect.