Let’s say I have a list of objects and that I’m extracting and modifying an item from the list like this:
List<MyObject> TheListOfObjects = new List<MyObject>();
MyObject TheObject = new MyObject();
TheListOfObjects = //some json deserialization result
TheObject = (from o in TheListOfObject
where o.ID == SomeParameter
select o).SingleOrDefault();
TheObject.SomeProperty = SomeValue;
When I write TheObject.SomeProperty = SomeValue; am I:
- modifying the item in the list and in which case I’m done or
- modifying a new item and I must replace the original item in the list with the item I just modified.
Depends.
If the list of objects is a list of class instances, then
TheObjectvariable will hold a value that is a reference. This reference will also still exist within the list. Modifications of the object at that reference will be visible in both. Important caveat: Writing over the reference contained in the variable (ie., variable reassignment) would not persist to the list, nor would writing over the reference in the list persist to the variable.If the list of objects is a list of struct instances, then
TheObjectsimply contains the value, and mutations of that value are not visible inside the list.