One of the pit­falls with LINQ which I have fallen into on mul­ti­ple occa­sions is around the use of the OfType<T> exten­sion method with dictionaries.

Either through care­less­ness or changes to the under­ly­ing vari­able (a class prop­erty being changed from list to dic­tio­nary for instance) I have ended up using OfType<…> on a dic­tio­nary which com­piles fine but unless I’m specif­i­cally look­ing for KeyValuePair<TKey, TValue>, it’s not going to behave as I’d expected…

image

Curi­ously, how­ever, with most other IEnumerable<T> types Resharper is able to spot the dan­ger signs and give me a warning:

image

 

Turns out Resharper has a really nice fea­ture – Cus­tom Pat­terns – which I hadn’t been aware of until recently, that allows you to spec­ify your own pat­terns which can then trig­ger suggestions/warnings/errors etc. when matched against ele­ments of your code. I can now cre­ate a cus­tom pat­tern to find places where I have tried to use the OfType<T> exten­sion method against a dic­tio­nary, like the following:

image

image

 

Now, if we go back to the source code, you can see that Resharper has now picked up on my mis­take using my pattern:

image

and since we spec­i­fied a Replace pat­tern above we can even use the Resharper helper to quickly fix our code!

image

Share
  • http://bugsquash.blogspot.com Mauri­cio Scheffer

    Nice! Didn’t know about this fea­ture. Unfor­tu­nately, ReSharper is quite incon­sis­tent: on one hand it real­izes that OfType is unsafe and shows the warn­ing you men­tion, on the other hand it offers to refac­tor code with generic col­lec­tions to OfType ( http://youtrack.jetbrains.com/issue/RSRP-288523 ). Same thing with Cast. Since these can freely down­cast, IMHO they should only be used on the old non-generic col­lec­tion types.