Reputation: 3532
I have a member variable which is a list of reference types. In a method I create and item, add it to the list. The item is then updated point to another instance but the instance in the list does not get updated (his is in some unit test code). Example looks like
Item localItem = new Item(arg1, arg2);
this.itemList.Add(localItem);
// Do some testing and assertions
localItem = new Item(arg3, arg4); // This does not update the instance of
// localItem in this.ItemList
// Do some more testing and assertions
I can update my tests to fix this but it still caught me by surprise. I supose the List wants to keep the original instance passed through the Add
method and cares not if the local variable which was used to pass it in now points to something else. Can anyone maybe confirm this understanding or explain it more clearly?
Upvotes: 3
Views: 3248
Reputation: 112382
Ofcourse not. The localItem
is a reference to the actual object (not the object itself). The list contains also a reference to this same object. If you assign another item to localItem
it now points to another object but the list has still a reference to the old object.
If you want the object in the list to update automatically you must introduce a new object that holds a reference to the item and add this one to the list
public class ItemReference
{
public Item Item { get; set; }
}
Now you can create a local item like this
ItemReference itemRef = new ItemReference();
itemRef.Item = new Item(arg1, arg2);
this.itemReferenceList.Add(itemRef);
itemRef.Item = new Item(arg3, arg4);
Because the list now has a reference to the same (unchanged) itemRef
it "sees" the new item as well.
The list has to be declared as
List<ItemReference> itemReferenceList;
Upvotes: 6
Reputation: 160912
When you add localItem
to the list you add a reference to the object instance (assuming Item
is a reference type aka a class
) - when you subsequently create a new Item
instance the result is a new reference (similar to a pointer) - if you want to update the list you have to remove the old item and add the new item - these are two totally different instances. Alternatively you can modify any properties on localItem
and these will be reflected when you access the item through the list.
Upvotes: 3