Runtime: Do not use OfType<T>() with impossible types

Created on 19 Mar 2020  路  5Comments  路  Source: dotnet/runtime

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

api-approved area-System.Linq code-analyzer

Most helpful comment

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.

```c#
Enumerable.Range(1, 100).OfType();

// @jnyrup points out that this is actually a non-null check,
// so isn't completely safe to remove

// myString.Split(",").OfType();
```

All 5 comments

Estimates:

  • Analyzer: Small
  • Fixer: Not Applicable

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.

```c#
Enumerable.Range(1, 100).OfType();

// @jnyrup points out that this is actually a non-null check,
// so isn't completely safe to remove

// myString.Split(",").OfType();
```

I did a little prototype for fun over at https://github.com/dotnet/roslyn-analyzers/issues/3608

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

Video

Approved as proposed

Category: Reliability
Suggested severity: Warning

Was this page helpful?
0 / 5 - 0 ratings

Related issues

chunseoklee picture chunseoklee  路  3Comments

EgorBo picture EgorBo  路  3Comments

matty-hall picture matty-hall  路  3Comments

aggieben picture aggieben  路  3Comments

iCodeWebApps picture iCodeWebApps  路  3Comments