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?
return i++
, the value of i (which is 0) returned before it gets incremented. While the increment may happen, the value is discarded because it is returned already. Try doingreturn ++i;
instead. – Numerologyi
which is aref
while I do know why the value 0 would be returned in a 'normal' case, I don't know why it would get up to 1 then back down to 0 – Philbrick