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

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…

image

Curiously, however, with most other IEnumerable<T> types Resharper is able to spot the danger signs and give me a warning:

image

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:

image

image

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

image

and since we specified a Replace pattern above we can even use the Resharper helper to quickly fix our code!

image

  • http://bugsquash.blogspot.com Mauricio Scheffer

    Nice! Didn’t know about this feature. Unfortunately, ReSharper is quite inconsistent: on one hand it realizes that OfType is unsafe and shows the warning you mention, on the other hand it offers to refactor code with generic collections to OfType ( http://youtrack.jetbrains.com/issue/RSRP-288523 ). Same thing with Cast. Since these can freely downcast, IMHO they should only be used on the old non-generic collection types.