I understand the differences between i++ and ++i, but I\'m not quite sure why I\'m getting the results below:
static void Main(string[] args)
{
int c = 4
The docs say for postfix state:
The result of the operation is the value of the operand before it has been incremented.
This means that when you do:
c = c++;
You're actually re-assigning 42 to c, and that's why you're seeing the console print 42. But if you do:
static void Main(string[] args)
{
int c = 42;
c++;
Console.WriteLine(c);
}
You'll see it output 43.
If you look at what the compiler generates (in Debug mode), you'll see:
private static void Main(string[] args)
{
int num = 42;
int num2 = num;
num = num2 + 1;
num = num2;
Console.WriteLine(num);
}
Which shows the overwrite more clearly. If you look at Release mode, you'll see the compiler optimize the entire call to:
private static void Main(string[] args)
{
Console.WriteLine(42);
}