Take a look at the following program:
class Test
{
List myList = new List();
public void TestMethod()
{
myList.Add
There are two parts of memory allocated for an object of reference type. One in stack and one in heap. The part in stack (aka a pointer) contains reference to the part in heap - where the actual values are stored.
When ref keyword is not use, just a copy of part in stack is created and passed to the method - reference to same part in heap. Therefore if you change something in heap part, those change will stayed. If you change the copied pointer - by assign it to refer to other place in heap - it will not affect to origin pointer outside of the method.
Here is an easy way to understand it
Your List is an object created on heap. The variable myList
is a
reference to that object.
In C# you never pass objects, you pass their references by value.
When you access the list object via the passed reference in
ChangeList
(while sorting, for example) the original list is changed.
The assignment on the ChangeList
method is made to the value of the reference, hence no changes are done to the original list (still on the heap but not referenced on the method variable anymore).