Spot the bug


Written on Friday, August 27, 2010 by
What is wrong with the code below? Safe Assumptions:
  1. _dictionary is a valid non-null Dictionary<object,object>
  2. _dictionary contains items that will match the passed expression
  3. This code compiles with no warnings or errors
  4. This code will throw an exception at runtime.

public IList<TModel> GetAllByCriteria<TModel> ( Expression<Func<TModel, bool>> criteria )
{
    Func<TModel, bool> action = criteria.Compile();
    return _dictionary.Where( pair => 
        action( (TModel)pair.Value ) ).Cast<TModel>().ToList();
}
If you don’t see it right away then you’re not alone. I spent a while debugging to catch this. If you do see it right away then pat yourself on the back.
Back

Let's talk about this

 


The opinions expressed herein are my own and do not represent my employer's view in any way.


Creative Commons License