I have a list of apples
, and I find those which are red:
var redApples = apples.Where(a => a.colour == "red");
redApples
is an IEnumerable
here, so if I convert this to a list:
var redApplesList = redApples.ToList();
This gives me a list of new objects. So if I modify these objects:
redApplesList.ForEach(a => a.color = "blue");
I would not expect the items in my original apples
list to change colour at all. But this isn't what happens, the apples in my original list which were "red"
are now "blue"
.
What is the misunderstanding here?
I was under the impression ToList()
created a completely new list of items independent from existing lists, but this suggests the pointers in the original list were updated to point to the newly created objects? Is this what's happening under the hood?
A lot of developers seem to resort to separating things out into separate lists (or even cloning objects) because they're never 100% sure what they're working with. It would be helpful to have a confident understanding of this area.