One of the pitfalls with LINQ which I have fallen into on multiple occasions is around the use of the OfType<T> extension method with dictionaries.
Either through carelessness or changes to the underlying variable (a class property being changed from list to dictionary for instance) I have ended up using OfType<…> on a dictionary which compiles fine but unless I’m specifically looking for KeyValuePair<TKey, TValue>, it’s not going to behave as I’d expected…
Curiously, however, with most other IEnumerable<T> types Resharper is able to spot the danger signs and give me a warning:
Turns out Resharper has a really nice feature – Custom Patterns – which I hadn’t been aware of until recently, that allows you to specify your own patterns which can then trigger suggestions/warnings/errors etc. when matched against elements of your code. I can now create a custom pattern to find places where I have tried to use the OfType<T> extension method against a dictionary, like the following:
Now, if we go back to the source code, you can see that Resharper has now picked up on my mistake using my pattern:
and since we specified a Replace pattern above we can even use the Resharper helper to quickly fix our code!
Subscribe to my newsletter and get new contents delivered straight to your inbox :-)