layout | status | title | slug |
---|---|---|---|
post |
publish |
Spot the bug |
Spot-the-bug |
What is wrong with the code below?
Safe Assumptions:
-
_dictionary
is a valid non-nullDictionary<object,object>
-
_dictionary
contains items that will match the passed expression -
This code compiles with no warnings or errors
-
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.