System.Linq.Enumerable

Cast<TResult> Method

Namespace: System.Linq

Projects each element of a sequence into a new form.

Syntax

public static System.Collections.Generic.IEnumerable<TResult> Cast<TResult>(this System.Collections.IEnumerable source)

Parameters

  • source An whose elements to project.

Returns

An that projects each element of the sequence into the specified type.

Remarks

The Cast<TResult> extension method can be used to cast all elements in an to the specified type. This is useful when you have a collection of objects of a base type and you want to work with them as a collection of a derived type.

For example, if you have a list of and you know that each object is actually a , you can use Cast<int>() to get an .

Note that this method performs a runtime cast. If an element in the source sequence cannot be cast to TResult, an will be thrown.

Example


using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

public class Example
{
    public static void Main(string[] args)
    {
        // Create a non-generic collection of objects.
        ArrayList objectList = new ArrayList();
        objectList.Add(10);
        objectList.Add(20);
        objectList.Add(30);

        // Cast the elements to integers using Cast<int>().
        IEnumerable<int> integerList = objectList.Cast<int>();

        // Iterate through the casted list and print the elements.
        Console.WriteLine("Elements after casting:");
        foreach (int number in integerList)
        {
            Console.WriteLine(number);
        }

        // Example with incompatible types (will throw InvalidCastException)
        ArrayList mixedList = new ArrayList();
        mixedList.Add(1);
        mixedList.Add("hello"); // This will cause an exception

        try
        {
            IEnumerable<int> invalidCastList = mixedList.Cast<int>();
            foreach (var item in invalidCastList)
            {
                Console.WriteLine(item);
            }
        }
        catch (InvalidCastException ex)
        {
            Console.WriteLine($"\nCaught expected exception: {ex.Message}");
        }
    }
}
                    

Exceptions

  • : is null.
  • : An element in the source sequence cannot be cast to type TResult.