What exactly happens when adding an object to a collection such as List?
List<Person> people = new List<Person>();
Person dan = new Person() { Name="daniel", Age=10 };
people.Add(dan);
dan = new Person() { Name = "hw", Age = 44 };
When I execute the above code, the List<Person> peopledoes not get affected by final line.
So I am assuming that the list copies the references of the added object, so when change the reference, the list does not get affected. am I correct?
Well, the code you’ve shown doesn’t actually add anything to the list at all. I assume you meant to have:
in there somewhere?
But yes, the
List<T>contains references to objects. It doesn’t know about where the references have come from. It’s worth being clear about the difference between a variable and its value. When you call:that copies the value of the argument expression (
dan) in this case as the initial value of the parameter withinList<T>.Add. That value is just a reference – it has no association with thedanvariable, other than it happened to be the value of the variable at the time whenList<T>.Addwas called.It’s exactly the same as the following situation:
Here, the value of
p2will still be a reference to the person with the name “Jon” – the second line just copies the value ofp1top2rather than associating the two variables together. Once you understand this, you can apply the same logic to method arguments.