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:
- If you want a one-stop shop to help you quickly level up your serverless skills, you should check out my Production-Ready Serverless workshop. Over 20 AWS Heroes & Community Builders have passed through this workshop, plus 1000+ students from the likes of AWS, LEGO, Booking, HBO and Siemens.
- If you want to learn how to test serverless applications without all the pain and hassle, you should check out my latest course, Testing Serverless Architectures.
- If you’re a manager or founder and want to help your team move faster and build better software, then check out my consulting services.
- If you just want to hang out, talk serverless, or ask for help, then you should join my FREE Community.
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.