3

I've found a really cool feature of a compilator. However, I cannot understand logic of this behaviour.

static int IncrementValue(ref int i) { return i++;}

and Main method:

static void Main(string[] args)
{
    int a = 2;
    int b = IncrementValue(ref a);
    Console.WriteLine(a+b);
} 

The output is 5.

My question is:

  1. Why is "b" field equal 2? (In my view, it ought to be 3 as "ref" keyword is not copying by value, but the keyword takes field by value. Consequently, "b" should be as "a+1")
Patrick Hofman
  • 148,824
  • 21
  • 237
  • 306
StepUp
  • 30,747
  • 12
  • 76
  • 133

2 Answers2

5

Since you wrote it as;

return i++

This will still return 2 as a value but it will increase a value to 3 after the expression.

If you wrote it as;

return ++i

This will return incremented value which is 3, and since a will be 3 after the execute it, it will be printed 6 as a result.

Further reading

Community
  • 1
  • 1
Soner Gönül
  • 94,086
  • 102
  • 195
  • 339
  • Not really *after it returns*, but after the expression has determined its value. Basically the statement will be executed as follows: Read the current value of `i`, then increment `i`, then return the value we read before we incremented it. Returning is still the last thing that is done in that method. – Lasse V. Karlsen Mar 12 '15 at 14:17
  • @LasseV.Karlsen Yes, _after the expression_ is much clear explanation. Since English is not my mother language, sometimes I can't express myself properly. – Soner Gönül Mar 12 '15 at 14:45
1

i++ is the post increment operator. It will increment the value afterwards, instead of before the value is returned.

Change i++ to ++i to make it increment before the value is returned, or increment the value in a separate statement and then return the value:

static int IncrementValue(ref int i) { return ++i; }

Or:

static int IncrementValue(ref int i) { i++; return i; }

(The reason you see different values when returning the integer, is that the result is copied. It is not a reference, else the return statement would not be useful at all).

Patrick Hofman
  • 148,824
  • 21
  • 237
  • 306