Home >Backend Development >C#.Net Tutorial >C# List Value Change Demonstration and Explanation Passed as Parameter
[TestMethod] public void TestMethod1() { List<int> list = new List<int>(); Test(list); Console.WriteLine(list.Count()); // 总数量变为 1 } private void Test(List<int> list) { list.Add(1); }
You can find that after Test, the number of elements in the list has changed from 0 to 1.
If the variable list is assigned to another variable list2, the list will also change when list2 is operated.
This is because these variables actually point to another memory block, and changes to the number of elements and element values all change the corresponding memory block.
But when their ConvertAll method is called, the returned variable points to another memory block, which is different from the previous one.
[TestMethod] public void TestMethod1() { List<int> list = new List<int>(); Test(list); Console.WriteLine(list.Count()); // 总数量仍为 0 } private void Test(List<int> list) { List<int> list2 = new List<int>(); list2.Add(1); list = list2; }
The above code is different. This is list = list2, which actually points the list to the memory block corresponding to list2. According to the previous conclusion, the list in the parameter is the same as list2, not TestMethod1. A group of people in the list.
The following code is different, but now it actually creates two new Listbd43222e33876353aff11e13a7dc75f6(), and no one in TestMethod1() uses it anymore.
[TestMethod] public void TestMethod1() { List<int> list = new List<int>(); Test(ref list); Console.WriteLine(list.Count()); // 总数量变为 1 } private void Test(ref List<int> list) { List<int> list2 = new List<int>(); list2.Add(1); list = list2; }
The same is true for arrays.
For more C# List value change demonstration and explanation related articles, please pay attention to the PHP Chinese website!