LINQ Interview Question #134

What is the purpose of OfType<T> in LINQ?

Advanced LINQ, Practical Problems & Senior Interview Scenarios Senior Advanced

Quick Interview Answer

OfType<T> filters a non-generic or mixed sequence to elements that are compatible with T and returns them strongly typed. Elements of other types are ignored.

Detailed Explanation

OfType<T> filters a non-generic or mixed sequence to elements that are compatible with T and returns them strongly typed. Elements of other types are ignored.

It is safer than assuming every element can be cast when the source intentionally contains mixed types.

Code Example

object[] values =
{
    10, "LINQ", 20, "C#"
};

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

// 10, 20