Skip to content
Tutorials Center
My learning

Topics

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.

C#
IEnumerable<int> ints = arrayList.Cast<int>();
IEnumerable<Dog> dogs = animals.OfType<Dog>();

Try it

C# Filter by type

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.

C# Old collections and LINQ

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

C#
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 foreach or ToList(), not at the Cast<T>() call.
  • Which one? Use Cast<T>() when you are certain about the type and want failures to be loud. Use OfType<T>() when mixed content is expected.
  • Not a numeric converter. Cast<double>() over boxed int values throws; unboxing needs the exact type. Convert with Select(Convert.ToDouble) or Select(x => (double)(int)x) instead.
  • null handling. OfType<T>() skips null for every T. Cast<string>() keeps null (it is a valid string reference) but Cast<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 source calls Cast<int>() for you. See query syntax.
  • Generics have a cheaper path. For IEnumerable<Base>, pattern-matching in a Select() or Where(x => x is Derived) is equivalent but gives you more control.
  • EF-style providers translate OfType<T>() into a type filter in some cases, but Cast<T>() is rarely translatable. Check the provider's documentation.