When you tried it with int
, a copy of the int variable was passed. For the time you ran the method your memory contained two ints, you modified one which was then thrown away
Had you passed the int
with ref
the original int would have been passed and the method would have modified the original value
When you pass objects, a reference to the object is passed and whether you use ref
or not you can modify properties of the object and the calling method will see those modifications. The difference with using ref or not on an object is that with ref you can swap the object for a whole new one (with new
) keyword and the original method will get the new object. Without ref, the original method will retain the original object because the reference that was passed (and subsequently changed for a new object) was a copy
Forget calling a method for a moment, let's do it simpler:
int x = 0;
int y = x;
y++;
What value do you now expect x to have?
It has 0; y is a copy of the value x has
Person p = new Person(){ Name = "John" };
Person q = p;
q.Name = "Mary";
What name do you expect p now to have? (It's Mary)
This is like what is happening with your posted code, so you already understand it in the context of not calling a method - y is a copy of x (and they refer to different data in memory, changing one does not change the other), q is a copy of a reference to p (but they both refer to the same data in memory, changing the data means both references see the change)