1

I am a little confused about the following behaviour:

int a = 3;
a++;
in b = a;

I understand that when you do a++ it will add a 1 which makes a = 4 and now b equals a so they are both 4.

int c = 3;
int d = c;
c++

But, here it tells me that c is 4 and d is 3. Since c++ makes c = 4; wouldn't d = 4; too?

ayhan
  • 70,170
  • 20
  • 182
  • 203
Yur Nazo
  • 33
  • 1
  • 3
  • 1
    Possible duplicate of [C# reference assignment operator?](http://stackoverflow.com/questions/7844791/c-sharp-reference-assignment-operator) – Maksim Simkin Nov 26 '16 at 09:20

1 Answers1

6

This line:

int d = c;

says "Declare a variable called d, of type int, and make its initial value equal to the current value of d."

It doesn't declare a permanent connection between d and c. It just uses the current value of c for the initial value of d. Assignment works the same way:

int a = 10;
int b = 20; // Irrelevant, really...
b = a;      // This just copies the current value of a (10) into b
a++;
Console.WriteLine(b); // Still 10...
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Essentially because int is a value type not a reference type – TheLethalCoder Nov 26 '16 at 09:19
  • 1
    @TheLethalCoder: Even with reference types, you're only copying the value from one variable to another... Changing the value of one variable won't change the value of the other. Modifying the object both variables' values refer to is a different matter. – Jon Skeet Nov 26 '16 at 09:49