Take a look at the following program:
class Test { List<int> myList = new List<int>(); public void TestMethod() { myList.Add(100); myList.Add(50); myList.Add(10); ChangeList(myList); foreach (int i in myList) { Console.WriteLine(i); } } private void ChangeList(List<int> myList) { myList.Sort(); List<int> myList2 = new List<int>(); myList2.Add(3); myList2.Add(4); myList = myList2; } }
I assumed that myList would go through ref and the result would be
3 4
The list is really "accepted by ref", but only the sort function is valid. The following statement is myList = myList2; has no effect.
Thus, the conclusion:
10 50 100
Can you help me explain this behavior? If really myList not passed in-ref (as it can be seen from myList = myList2 does not work), how does myList.Sort() ?
I assumed that this statement does not enter into force, and the output will be:
100 50 10
list pass-by-reference c #
Ngm Nov 30 '10 at 6:49 2010-11-30 06:49
source share