All rules
CA2021Reliability Enabled by default: As warning

Don't call Enumerable.Cast<T> or Enumerable.OfType<T> with incompatible types

Don't call Enumerable.Cast<T> or Enumerable.OfType<T> with incompatible types

Microsoft docs

Description

System.Linq.Enumerable.Cast`1(System.Collections.IEnumerable) and System.Linq.Enumerable.OfType`1(System.Collections.IEnumerable) require compatible types to produce the expected result:

  • The generic cast used by the sequence returned by System.Linq.Enumerable.Cast``1(System.Collections.IEnumerable) throws an System.InvalidCastException at runtime on elements of incompatible types.
  • The generic type check used by System.Linq.Enumerable.OfType``1(System.Collections.IEnumerable) won't succeed with elements of incompatible types, resulting in an empty sequence.

Widening and user-defined conversions aren't supported with generic types.

Cause

A call to System.Linq.Enumerable.Cast`1(System.Collections.IEnumerable) or System.Linq.Enumerable.OfType`1(System.Collections.IEnumerable) specifies a type parameter that's incompatible with the type of the input collection.

How to fix violations

Use a compatible type for the type parameter of System.Linq.Enumerable.Cast`1(System.Collections.IEnumerable) and System.Linq.Enumerable.OfType`1(System.Collections.IEnumerable).

Example

var foods = new List<Food>();
// Violation - Food is incompatible with Beverages.
var drinks = Enumerable.Cast<Beverages>(foods);
// Violation - Food is incompatible with Beverages.
var drinks2 = Enumerable.OfType<Beverages>(foods);

class Food { }
class Bread : Food { }
class Beverages { }

var foods = new List<Food>();
// Bread is compatible with Food.
var breads = Enumerable.Cast<Bread>(foods);
// Bread is compatible with Food.
var breads2 = Enumerable.OfType<Bread>(foods);

class Food { }
class Bread : Food { }
class Beverages { }

When to suppress

You shouldn't suppress warnings from this rule, as you'll either encounter runtime exceptions or unexpected behavior (empty sequences).

Group results
0 yes 0 no
ConsensusNone (disabled)
Severity preference (yes voters)
Suggestion0
Warning0
Error0