I needed to verify this in linqpad but this code evaluates to 0 the first time. Why does this occur in C#?
var integer = 0;
while(true){
var @string = integer++.ToString();
Console.WriteLine(@string);
}
I also verified that evaluates to 1 first.
var integer = 0;
while(true){
var @string = (++integer).ToString();
Console.WriteLine(@string);
}
I get the difference between ++x and x++. just was expecting it to do x++ and then the ToString() gets called.
My understanding of the post increment operator is that it first saves the value of the variable (i
in this case), increments i
and then uses the saved value (in this example, in the call to ToString()
).
This code:
int i = 5;
string s = i++.ToString();
is equivalent to:
int i = 5;
int temp = i;
i = i + 1;
var s = temp.ToString();
You can use LinqPad or other tool (ILSpy, etc.) to look at the IL:
IL_0000: nop
IL_0001: ldc.i4.5
IL_0002: stloc.0 // i
IL_0003: ldloc.0 // i
IL_0004: dup
IL_0005: ldc.i4.1
IL_0006: add
IL_0007: stloc.0 // i
IL_0008: stloc.2 // CS$0$0000
IL_0009: ldloca.s 02 // CS$0$0000
IL_000B: call System.Int32.ToString
IL_0010: stloc.1 // s
IL_0011: ret
Here's a blog post by Eric Lippert with more information