System.Linq.Enumerable
Cast<TResult> Method
Namespace: System.LinqProjects each element of a sequence into a new form.
Syntax
Parameters
- source
An
whose elements to project.
Returns
An
Remarks
The Cast<TResult>
extension method can be used to cast all elements in an
For example, if you have a list of 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
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
.