Resharper – Using custom patterns to catch subtle bugs with OfType<T>

One of the pit­falls with LINQ which I have fall­en into on mul­ti­ple occa­sions is around the use of the OfType<T> exten­sion method with dic­tio­nar­ies.

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

image

Curi­ous­ly, how­ev­er, with most oth­er IEnumerable<T> types Resharp­er is able to spot the dan­ger signs and give me a warn­ing:

image

Turns out Resharp­er has a real­ly nice fea­ture – Cus­tom Pat­terns – which I hadn’t been aware of until recent­ly, that allows you to spec­i­fy 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 fol­low­ing:

image

image

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

image

and since we spec­i­fied a Replace pat­tern above we can even use the Resharp­er helper to quick­ly fix our code!

image