New Analyzer: Warn when calling Enumerable.Cast<T>/OfType<T> with incompatible types #3608
Labels
help wanted
The issue is up-for-grabs, and can be claimed by commenting
Milestone
The following will always throw an
InvalidCastException
at runtime:new int[] { 1 }.Cast<string>().ToList();
new float[] { 1f }.Cast<double>().ToList();
new int[] { 1 }.Cast<long>().ToList();
Perhaps worse, this will return an enumerable that fully enumerates the source and then returns no items silently:
enumerableOfApple.OfType<Orange>()
Both of these situations are likely to be a mistake.
I'd never played with Roslyn before but I thought it'd be fun so I hacked together something. The rules seem quite complex so I have no confidence I got it right - or even if it's possible to spot 100% of cases - but it seems to be able to pick up the most obvious problems and I think that's still valuable.
Also, naming things and writing descriptive messages is really hard 😅.
An interesting thing I learnt was that enums can be cast to/from their underlying type and to other enums with the same underlying type this way, but numeric types can't be. I guess the numeric type conversions must be a language thing and so the compiled
Cast<T>()
can't know them.Anyway I hope this is useful, even just for the idea.
Thanks
PS. It's amazing how good the getting started docs are here! (The comments in the code are a little sparse though ;))
The text was updated successfully, but these errors were encountered: