C# List internals

后端 未结 5 1266
渐次进展
渐次进展 2021-01-07 05:47

What exactly happens when adding an object to a collection such as List?

List people = new List();
Person dan = new Person() { Na         


        
5条回答
  •  旧时难觅i
    2021-01-07 06:18

    To answer the original question, assuming you intended to add the person to the list before calling the third line:

    Yes, the list only stores a reference to the object. In C#, ALL object variables are references.

    So when you call new Person() a second time, the reference held by your variable dan is updated to point to the new instance. If the first instance has no reference pointed to it, it will be garbage collected in the next round. If you had added the first instance to the list, the list would still retain it's reference to the first instance.

提交回复
热议问题