Search code examples
c#incrementoperator-precedenceref

Interesting interview exercise result: return, post increment and ref behavior


Here's a simple console application code, which returns a result I do not understand completely.

Try to think whether it outputs 0, 1 or 2 in console:

using System;

namespace ConsoleApplication
{
    class Program
    {
        static void Main()
        {
            int i = 0;
            i += Increment(ref i);

            Console.WriteLine(i);
            Console.ReadLine();
        }

        static private int Increment(ref int i)
        {
            return i++;
        }
    }
}

The answer is 0.

What I don't understand is why post increment i++, from the Increment method, which is executed on a ref (not on a copy of the passed variable) does increment the variable, but it just gets ignored later.

What I mean is in this video:

Can somebody explain this example and why during debug I see that value is incremented to 1, but then it goes back to 0?


Solution

  • i += Increment(ref i); is equivalent to

    i = i + Increment(ref i);
    

    The expression on the right hand side of the assignment is evaluated from left to right, so the next step is

    i = 0 + Increment(ref i);
    

    return i++ returns the current value of i (which is 0), then increments i

    i = 0 + 0;
    

    Before the assignment the value of i is 1 (incremented in the Increment method), but the assignment makes it 0 again.