What exactly happens when adding an object to a collection such as List?
List people = new List();
Person dan = new Person() { Na
Well, the code you've shown doesn't actually add anything to the list at all. I assume you meant to have:
people.Add(dan);
in there somewhere?
But yes, the List
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:
people.Add(dan);
that copies the value of the argument expression (dan
) in this case as the initial value of the parameter within List
. That value is just a reference - it has no association with the dan
variable, other than it happened to be the value of the variable at the time when List
was called.
It's exactly the same as the following situation:
Person p1 = new Person { Name = "Jon" };
p2 = p1;
p1 = new Person { Name = "Dan" };
Here, the value of p2
will still be a reference to the person with the name "Jon" - the second line just copies the value of p1
to p2
rather than associating the two variables together. Once you understand this, you can apply the same logic to method arguments.