C# Reference ยท LINQ
LINQ Cast() and OfType() methods
Reference for LINQ Cast<T>() and OfType<T>() in C#: convert non-generic collections, filter mixed sequences by type and avoid InvalidCastException.
Cast<T>() and OfType<T>() turn a sequence of one element type into a sequence of another. Cast<T>() converts every element and throws if any element is not a T. OfType<T>() keeps only the elements that are a T and silently skips the rest.
They are the bridge between old non-generic collections (ArrayList, IEnumerable, MatchCollection in older code) and LINQ, which needs IEnumerable<T>. They are also the quick way to filter a heterogeneous List<object> or a list of base-class instances by derived type.
IEnumerable<int> ints = arrayList.Cast<int>(); IEnumerable<Dog> dogs = animals.OfType<Dog>();
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Syntax
public static IEnumerable<TResult> Cast<TResult>(this IEnumerable source); public static IEnumerable<TResult> OfType<TResult>(this IEnumerable source);
| Name | Description |
|---|---|
TResult |
The type to convert to (Cast) or to keep (OfType). |
source |
A non-generic IEnumerable; any IEnumerable<T> qualifies too. |
Returns: a lazily evaluated IEnumerable<TResult>. If source already is an IEnumerable<TResult>, Cast<T>() may return it as is.
Errors: ArgumentNullException if source is null (thrown immediately). Cast<T>() throws InvalidCastException during enumeration for an element that cannot be converted, including null when TResult is a non-nullable value type.
Usage notes
- Deferred execution. Both methods stream: a bad element is only noticed when enumeration reaches it, so the exception can appear in a later
foreachorToList(), not at theCast<T>()call. - Which one? Use
Cast<T>()when you are certain about the type and want failures to be loud. UseOfType<T>()when mixed content is expected. - Not a numeric converter.
Cast<double>()over boxedintvalues throws; unboxing needs the exact type. Convert withSelect(Convert.ToDouble)orSelect(x => (double)(int)x)instead. nullhandling.OfType<T>()skipsnullfor everyT.Cast<string>()keepsnull(it is a valid string reference) butCast<int>()throws on it.- Subtypes count.
OfType<Animal>()returns dogs and cats alike;OfType<Dog>()returns only dogs and their subclasses. - Query syntax.
from int x in sourcecallsCast<int>()for you. See query syntax. - Generics have a cheaper path. For
IEnumerable<Base>, pattern-matching in aSelect()orWhere(x => x is Derived)is equivalent but gives you more control. - EF-style providers translate
OfType<T>()into a type filter in some cases, butCast<T>()is rarely translatable. Check the provider's documentation.