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

Yan Cui

I help clients go faster for less using serverless technologies.

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

Whenever you’re ready, here are 3 ways I can help you:

  1. Production-Ready Serverless: Join 20+ AWS Heroes & Community Builders and 1000+ other students in levelling up your serverless game. This is your one-stop shop to level up your serverless skills quickly.
  2. Do you want to know how to test serverless architectures with a fast dev & test loop? Check out my latest course, Testing Serverless Architectures and learn the smart way to test serverless.
  3. I help clients launch product ideas, improve their development processes and upskill their teams. If you’d like to work together, then let’s get in touch.

1 thought on “Resharper – Using custom patterns to catch subtle bugs with OfType<T>”

  1. 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.

Leave a Comment

Your email address will not be published. Required fields are marked *