Skip to content

Do not use OfType<T>() with impossible types #33770

@terrajobst

Description

@terrajobst

Warn if use of OfType<T>() would provably result in an empty sequence, because we can see that the input type in the sequence will never be the specified type.

Category: Reliability
Suggested severity: Warning

UPDATE FROM roslyn-analyzer issue :

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.

Ther is a PR out for review

Metadata

Metadata

Assignees

Labels

api-approvedAPI was approved in API review, it can be implementedarea-System.Linqcode-analyzerMarks an issue that suggests a Roslyn analyzerin-prThere is an active PR which will close this issue when it is merged

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions