Cast<TResult> Method

Converts an IEnumerable to an IEnumerable<TResult>.

Syntax

public static IEnumerable<TResult> Cast<TResult>(
    this IEnumerable source
);

Parameters

Name Type Description
source IEnumerable An IEnumerable whose elements to cast.

Type Parameters

Name Description
TResult The type to cast the elements of source to.

Returns

Type Description
IEnumerable<TResult> An IEnumerable<TResult> that contains elements of type TResult.

Remarks

The Cast<TResult> method iterates through the specified collection and casts each element to the specified type. This method is useful when you have a collection of objects that you know can be cast to a specific type, but the collection itself is not strongly typed.

If an element in the source collection cannot be cast to TResult, a runtime exception will be thrown.

Examples

Casting a list of integers to a list of strings.
using System;
using System.Collections;
using System.Linq;

public class Example
{
    public static void Main(string[] args)
    {
        ArrayList numbers = new ArrayList() { 1, 2, 3, 4, 5 };

        // Cast the ArrayList to IEnumerable<string>
        IEnumerable<string> stringNumbers = numbers.Cast<string>();

        // Note: This example will throw a runtime exception because integers cannot be directly cast to strings.
        // For a successful cast, the elements must be compatible.
        // For example, casting an ArrayList of strings to IEnumerable<string> would work.

        // Example of a successful cast:
        ArrayList stringList = new ArrayList() { "apple", "banana", "cherry" };
        IEnumerable<string> typedStringList = stringList.Cast<string>();

        Console.WriteLine("Successfully cast elements:");
        foreach (string s in typedStringList)
        {
            Console.WriteLine(s);
        }
    }
}