Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
C# Cast method
The Cast<T>() method in C# is a LINQ extension method used to cast each element in a collection from one type to another. It is particularly useful when working with collections of object type that need to be converted to a specific type for further processing.
Syntax
Following is the syntax for the Cast<T>() method −
public static IEnumerable<TResult> Cast<TResult>(this IEnumerable source)
Parameters
- source − The collection containing elements to be cast.
- TResult − The target type to cast elements to.
Return Value
Returns an IEnumerable<TResult> containing each element of the source sequence cast to the specified type.
Using Cast() with Object Collections
When you have a collection of object type containing elements of a specific type, Cast<T>() converts them back to their original type −
using System;
using System.Linq;
using System.Collections.Generic;
class Program {
static void Main() {
List<object> myList = new List<object> { "Mac", "Windows", "Linux", "Solaris" };
// Cast objects back to strings
IEnumerable<string> stringList = myList.Cast<string>();
foreach (string item in stringList) {
Console.WriteLine(item);
}
}
}
The output of the above code is −
Mac Windows Linux Solaris
Using Cast() with String Operations
Once cast to the proper type, you can chain additional LINQ methods like Select() to perform operations −
using System;
using System.Linq;
using System.Collections.Generic;
class Program {
static void Main() {
List<object> list = new List<object> { "keyboard", "mouse", "joystick", "monitor" };
// Cast to string and get first 2 letters from every string
IEnumerable<string> res = list.Cast<string>().Select(str => str.Substring(0, 2));
foreach (string str in res) {
Console.WriteLine(str);
}
}
}
The output of the above code is −
ke mo jo mo
Using Cast() with Numeric Types
The Cast<T>() method also works with numeric types and other data types −
using System;
using System.Linq;
using System.Collections;
class Program {
static void Main() {
ArrayList numbers = new ArrayList { 10, 20, 30, 40, 50 };
// Cast objects to integers and calculate sum
int sum = numbers.Cast<int>().Sum();
Console.WriteLine("Sum: " + sum);
// Cast and filter even numbers
var evenNumbers = numbers.Cast<int>().Where(x => x % 2 == 0);
Console.WriteLine("Even numbers:");
foreach (int num in evenNumbers) {
Console.WriteLine(num);
}
}
}
The output of the above code is −
Sum: 150 Even numbers: 10 20 30 40 50
Conclusion
The Cast<T>() method is essential for converting collections of object type to strongly-typed collections, enabling type-safe operations and LINQ method chaining. It throws an exception if any element cannot be cast to the specified type, so ensure all elements are compatible before casting.
