If I had guessed, I would say that this line ...
var item = _list.Where( o => o.OrderDetail.TrayCode == orderResponse.OrderDetail.TrayCode) .FirstOrDefault();
... because it calls FirstOrDefault() , it can return null . Set a breakpoint and see what really happens.
To this end, why make this request? Since you are passing the object to be deleted, why not just do this:
int index = _list.IndexOf(item); if (index >= 0) this._list.RemoveAt(index);
Even better, since List<T> has its own Remove(T object) method:
this._list.Remove(item); //this may throw an exception or not if the item is not in that collection, // which is behavior you should probably retain
Sidenotes
There is also a possible race condition in how you raise the CollectionChanged event. Between checking for null and raising the subscriber, the subscriber could remove the delegate from the event. Here is an easy way to avoid this:
// initialize it with an empty lamda so it is never null public event NotifyCollectionChangedEventHandler CollectionChanged = (o,e) => {};
Now you can just pick it up and no need to check if it is null:
public void Add(OrderResponse orderResponse) { this._list.Add(orderResponse); CollectionChanged(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, orderResponse, this._list.Count - 1)); }
This does not make it completely thread safe, but it is an easy way to make sure that raising the event will not result in a null reference exception.
Joel B Fant May 4 '11 at 13:52 2011-05-04 13:52
source share