C # List The value change passed as a parameter demonstration commentary

Source: Internet
Author: User
[testmethod]public void TestMethod1 () {    list<int> List = new list<int> ();    Test (list);    Console.WriteLine (list. Count ()); The total quantity becomes 1}private void Test (list<int> list) {    list. ADD (1);}

Can be found: After the Test, the list of the number of elements from 0 to 1.

If you assign a variable list to another variable list2, the list will change if you manipulate List2.

This is because these variables are actually pointing to another block of memory, and the change in the number of elements and the value of the element is the same block of memory that corresponds to the change.

But by calling their ConvertAll method, the returned variable is pointing to another block of memory, which is different from the previous one.

[testmethod]public void TestMethod1 () {    list<int> List = new list<int> ();    Test (list);    Console.WriteLine (list. Count ()); The total quantity is still 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 the list = List2, in fact, the list points to the list2 corresponding memory block, according to the previous conclusion, this time the list of parameters and List2 is a bunch, instead of and TestMethod1 in the list of the gang.

The following code is different, but now we have actually created two new list<int> () and no one is using it in TESTMETHOD1 ().

[testmethod]public void TestMethod1 () {    list<int> List = new list<int> ();    Test (ref list);    Console.WriteLine (list. Count ()); The total quantity becomes 1}private void Test (ref list<int> List) {    list<int> list2 = new list<int> ();    List2. ADD (1);        list = List2;}

Arrays are the same thing.


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.