Cause
A call to System.Linq.Enumerable.Cast(System.Collections.IEnumerable)](https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.cast--1) or [System.Linq.Enumerable.OfType(System.Collections.IEnumerable) specifies a type parameter that's incompatible with the type of the input collection.
Rule description
System.Linq.Enumerable.Cast(System.Collections.IEnumerable)](https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.cast--1) and [System.Linq.Enumerable.OfType(System.Collections.IEnumerable) require compatible types to produce the expected result:
- The generic cast used by the sequence returned by [System.Linq.Enumerable.Cast`(System.Collections.IEnumerable)](https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.cast--1) throws an System.InvalidCastException at runtime on elements of incompatible types.
- The generic type check used by [System.Linq.Enumerable.OfType`(System.Collections.IEnumerable)](https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.oftype--1) won't succeed with elements of incompatible types, resulting in an empty sequence.
Widening and user-defined conversions aren't supported with generic types.
How to fix violations
Use a compatible type for the type parameter of System.Linq.Enumerable.Cast(System.Collections.IEnumerable)](https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.cast--1) and [System.Linq.Enumerable.OfType(System.Collections.IEnumerable).
Example
The following code snippet shows violations:
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 { }' Violation - Integer is incompatible with String.
Dim a1 = (Array.Empty(Of Integer)()).Cast(Of String)
' Violation - Integer is incompatible with String.
Dim a1 = (Array.Empty(Of Integer)()).OfType(Of String)The following code snippet shows the fixes:
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 { }' Integer is compatible with Object.
Dim a1 = (Array.Empty(Of Integer)()).Cast(Of Object)
' Integer is compatible with Object.
Dim a1 = (Array.Empty(Of Integer)()).OfType(Of Object)When to suppress warnings
You shouldn't suppress warnings from this rule, as you'll either encounter runtime exceptions or unexpected behavior (empty sequences).