10 November 2008

List<T>.Find()

I am going to try to document issues that I found not intuitive or easy to figure out (which may or may not be sleep deprivation induced), so here is my latest with an issue with List<T>.Find().

With the List<T>.Find method, you are supposed to supply a predicate, which is really just a delegate with a boolean function determining if a match happened.  So, when would this fail?

List<IItem> items = new List<IItem>();



if (items.Find(item => item.ItemId == smi.ItemId) == null) {


    items.Add(csFacade.GetItemByItemId(smi.ItemId));


}




Answer:  when items contains a null.  My assumption going into this was that I would always get a valid result from the method adding to the items list, but it may return null. 



So, to solve this, I would either need to evaluate the return from GetItemByItemId and only add if not null, or change my predicate to check for null before comparing the ItemIds.

No comments: