4

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;
        }
Community
  • 1
  • 1
Bosak
  • 2,103
  • 4
  • 24
  • 43
  • Possible duplicate: http://stackoverflow.com/questions/10531829/how-to-overload-postfix-and-prefix-operator-in-c-sharp which is a dupe of http://stackoverflow.com/questions/668763/post-increment-operator-overloading – René Wolferink Nov 13 '12 at 17:29
  • 1
    As a general rule, overloaded operators should always return a new instance, not modify the current instance. – dthorpe Nov 13 '12 at 17:54

1 Answers1

4

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.

Ian Roberts
  • 120,891
  • 16
  • 170
  • 183
  • oh I got it now that's because I'm working with reference variables. What if Fly was not a class but struct? Then what I have written should work right? – Bosak Nov 13 '12 at 17:36
  • 4
    @Bosak It has nothing to do with whether it's a reference type or a value type. It has everything to do with whether it's mutable or immutable. If `Fly` was immutable (even as a class) then this would be fine. If it was a mutable struct, or a struct with fields that were references, you could potentially have problems. – Servy Nov 13 '12 at 17:41