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…
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!
Whenever you’re ready, here are 4 ways I can help you:
- 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 for quickly levelling up your serverless skills.
- 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.
- 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.
- Join my community on Discord, ask questions, and join the discussion on all things AWS and Serverless.
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.