In C# if an object in a list is added to another list, does changing the object in the second list change the same object in the first list?

前端 未结 2 1249
无人及你
无人及你 2021-01-24 13:01

Say I have a list of Person objects (List) called persons, like this:

class Person
{
    public int PersonId         


        
相关标签:
2条回答
  • 2021-01-24 13:07

    Since Person is a reference type (class) changing name on the item in the list will change the name on the Person object and all references to that object will now see the new name. If it was a struct that would not be the case.

    0 讨论(0)
  • 2021-01-24 13:27

    When you have a list of objects that are reference types and not value types, that is stored in the list is a reference for each object in the list. Hence if you add the same object to two different lists, you actually add to the second list the same reference. Hence if you make any change in the object, this would be "visible" from both lists.

    0 讨论(0)
提交回复
热议问题