I have a piece of code:
using System;
public class Program
{
private static int Incr(ref int i)
{
return i++;
}
public static void Main()
{
var i = 0;
i += Incr(ref i);
Console.WriteLine(i);
}
}
Console.WriteLine(i) will gives us "0". But calling Incr(ref i) without "+="
var i = 0;
Incr(ref i);
Console.WriteLine(i);
will give us "1". How is it possible?
Think of i += Incr(ref i)
as
i = i + Incr(ref i);
In other words:
i
Incr(ref i)
i
Now Incr(ref i)
sets i
to 1, but returns 0... so the sum ends up being 0 + 0, which is then assigned to i
. The value of i
is very temporarily 1, in the time between Incr
returning and the result being assigned back to i
.
If you had:
int j = i + Incr(ref i);
then you'd end up with j=0, i=1
.
When you just call Incr(ref i)
then Incr
increments i
(so i
is 1) and then the return value is ignored... so i
is 1 afterwards.
In other news: code like this should be avoided at all costs.
See more on this question at Stackoverflow