Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objects relationship in a list?

Tags:

c#

list

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>.

like image 689
Inx Avatar asked Jun 09 '26 05:06

Inx


1 Answers

The vital thing to remember is that a list does not contain objects. It contains references to objects. So if you do:

List<Foo> foos = GetListOfFooFromSomewhere();
Foo foo = foos[0];
foo.Name = "Some other name";

there's only one Foo object 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 Foo is 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.)

like image 189
Jon Skeet Avatar answered Jun 10 '26 18:06

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!