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?
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With