Skip to content

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

Closed

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

Activity

  1. added
    api-suggestion
    code-analyzer
    on Mar 19, 2020
  2. added
    untriaged
    on Mar 19, 2020
  3. added this to the Future milestone on Mar 20, 2020
  4. jeffhandley commented on Mar 21, 2020

    @jeffhandley
    Member

    Estimates:

    • Analyzer: Small
    • Fixer: Not Applicable
  5. removed
    untriaged
    on Mar 21, 2020
  6. drewnoakes commented on Jun 4, 2020

    @drewnoakes
    Member

    Possibly at the same time, though via a different diagnostic ID: calling OfType<T>() on an IEnumerable<T> where the T is identical or assignable is redundant.

    Enumerable.Range(1, 100).OfType<int>();
    
    // @jnyrup points out that this is actually a non-null check,
    // so isn't completely safe to remove
    
    // myString.Split(",").OfType<object>();
  7. fowl2 commented on Jun 4, 2020

    @fowl2

    I did a little prototype for fun over at dotnet/roslyn-analyzers#3608

  8. jnyrup commented on Jun 5, 2020

    @jnyrup
    Contributor

    @drewnoakes Note that for reference types this can be used as a less clear way of writingWhere(e => e != null).

  9. modified the milestones: Future, 6.0.0 on Sep 28, 2020
  10. added
    api-ready-for-review
    and removed
    api-suggestion
    on Nov 6, 2020
  11. bartonjs commented on Nov 10, 2020

    @bartonjs
    Member

    Video

    Approved as proposed

    Category: Reliability
    Suggested severity: Warning

  12. added
    api-approved
    and removed
    api-ready-for-review
    on Nov 10, 2020
  13. modified the milestones: 6.0.0, Future, 7.0.0 on Aug 13, 2021
  14. added
    in-pr
    on Jul 6, 2022
  15. modified the milestones: 7.0.0, Future on Jul 9, 2022
  16. modified the milestones: Future, 8.0.0 on Nov 9, 2022
  17. ghost locked as resolved and limited conversation to collaborators on Feb 26, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

api-approvedarea-System.Linqcode-analyzerin-pr

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions