C # ilist.tolist () changing element values will affect the value of the original list

Source: Internet
Author: User

classListtest { Public Static voidTest () {#regionValue typevarOlistval =Newlist<int>()            {                1,2,3,4            }; varNlistval = olistval.where (p = p >2).            ToList (); //because T is a value type (int type), the elements of the new list are assigned a memory address (stack memory) with the elements of the old list.//change the elements of a new list without affecting the old list elementsnlistval[0] =5; if(olistval[2] = = nlistval[0]) {Console.WriteLine ("value type--changed original value"); }            Else{Console.WriteLine ("value type--unchanged original value"); }            #endregion            #regionReference typevarOlistref =NewList<student>()            {                NewStudent () {Id=1, Name="A"                },                NewStudent () {Id=2, Name="B"                },                NewStudent () {Id=3, Name="C"                },                NewStudent () {Id=4, Name="D"                },            }; varNlistref = Olistref.where (p = p.id >2).            ToList (); //because T is a reference type (class type), the elements of the new list share a memory address (heap memory) with the elements of the old list//changes the elements of the new list, and actually modifies the old list elementsnlistref[0]. Name ="G"; if(olistref[2]. Name = = nlistref[0]. Name) {Console.WriteLine ("reference Type--changed original value"); }            Else{Console.WriteLine ("reference Type--unchanged original value"); }            #endregion        }        classStudent { Public intId {Get;Set; }  Public stringName {Get;Set; } }    }

C # ilist.tolist () changing element values will affect the value of the original list

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.