Now, I know this might be a newbie question, but I always screws this up.
I have a list containing a bunch of objects, but then later in my code I query the list to modify one of the objects using LINQ.
Will this update the object inside the list as well or will I have to remove the old instance of the object from the list and then place the object I pulled out back into the list to make sure that the changed values are stored in the list? The list is just a simple List<MyObject>.
The vital thing to remember is that a list does not contain objects. It contains references to objects. So if you do:
there’s only one
Fooobject involved – but both the list and the local variable have a reference to that same object. Changes to the object don’t need to be “propagated” to the list, because the list doesn’t have that data in the first place.An analogy I sometimes use is this: if I give two people my home address on pieces of paper, and one of them paints my front door red, then if the other person goes to my house, they’ll see a red front door. The pieces of paper are distinct, but they don’t contain “my house” – they just contain a way of getting to my house. There’s only one house.
(This is assuming
Foois a class, by the way. If you have a list of mutable structs, then the list really contains the data directly, not references. Personally I would avoid using mutable structs to start with.)