ReSharper 2024.1 Help

Code inspection: Redundant 'IEnumerable.Cast<T>' or 'IEnumerable.OfType<T>' call

This inspection reports unnecessary complexity when the Enumerable.Cast<T>() or Enumerable.OfType<T>() method is used on a collection that already guarantees that all its elements are of type T.

In the case of Cast<T>(), the call does not change the semantics and can be safely removed to improve clarity and readability.

In the case of OfType<T>(), removing the call can change the semantics of your code if the collection contains null values, because they will be filtered out by this call.

In the example below, the method will type all elements from list, that are not null. The rewritten version preserves the semantics, but better shows what is going on.

void CountRealStrings(List<string> list) { Console.WriteLine(list.OfType<string>().Count()); }
void CountRealStrings(List<string> list) { Console.WriteLine(list.Where(item => item != null).Count()); }
Last modified: 05 June 2024