Lesson 8/31

Tutorials LINQ Mastery

OfType vs Cast: Handling heterogeneous collections

On this page

Filtering by Type

When working with object collections (like UI controls or base class lists), you often need to grab just the specific types. OfType and Cast look similar but behave very differently.

1. OfType: The Secure Filter

OfType<T>() checks each element. If it matches the type, it yields it. If it DOESN'T match, it simply **skips** it gracefully. Use this when your list is a mix of types.

2. Cast: The Optimistic Transformer

Cast<T>() tries to force every element into the target type. If a single element fails to cast, it throws an InvalidCastException. Use this only when you are 100% sure the collection contains only that type.

3. Architect Insight

Q: "Which is better for legacy code?"

Architect Answer: "Legacy collections from .NET 1.1 (like ArrayList) don't support generics. Use **Cast** to convert them into IEnumerable<T> so you can use modern LINQ methods. For modern collections, prefer **OfType** as it's more resilient to unexpected data."

Questions on this lesson 0

Sign in to ask a question or upvote helpful answers.

No questions yet — be the first to ask!

LINQ Mastery
Course syllabus
General
1. Core Foundations
2. Filtering & Transformation
3. Aggregation & Quantifiers
4. Ordering & Partitioning
5. Sets & Lookups
6. Join & Grouping
7. Advanced Providers & Parallelism
8. Real-world Performance & Patterns
Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details