C#: When adding the same object to two List<object> variables, is the object cloned in the process?

后端 未结 7 1131
伪装坚强ぢ
伪装坚强ぢ 2021-01-01 19:28

I have something similar to this:

// Declarations:
List list1 = new List();
List list2 = new List

        
7条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-01 20:03

    // Declarations:
    List list1 = new List();
    List list2 = new List();
    
    ...
    
    SomeType something = new SomeType("SomeName");
    list1.Add(something);
    list2.Add(something);
    

    Remember, when you add an object to a list, you're really just adding a pointer to the object. In this case, list1 and list2 both point to the same address in memory.

    list1[indexOfSomething] = new SomeType("SomeOtherName");
    

    Now you've assigned the element list1 to a different pointer.

    You're not really cloning objects themselves, you're copying the pointers which just happen to be pointing at the same object. If you need proof, do the following:

    SomeType something = new SomeType("SomeName");
    list1.Add(something);
    list2.Add(something);
    
    list1[someIndex].SomeProperty = "Kitty";
    
    bool areEqual = list1[someIndex].SomeProperty == list2[someIndex].SomeProperty;
    

    areEqual should be true. Pointers rock!

提交回复
热议问题