LINQ Interview Question #135

What is the difference between Cast<T> and OfType<T>?

Advanced LINQ, Practical Problems & Senior Interview Scenarios Senior Advanced

Quick Interview Answer

Cast<T> attempts to cast every element to T and throws if an incompatible element is encountered. OfType<T> returns only elements that can be treated as T and skips incompatible values.

Detailed Explanation

Cast<T> attempts to cast every element to T and throws if an incompatible element is encountered. OfType<T> returns only elements that can be treated as T and skips incompatible values.

Use Cast when every element is expected to have the target type. Use OfType when filtering a heterogeneous sequence by type is intentional.

Code Example

object[] values = { 1, 2, "three" };

var onlyInts = values.OfType<int>();

// This throws when "three" is reached:
var allInts = values.Cast<int>();