The LINQ Cast Method in C# is used to casts all the elements of a collection (System.Collections.IEnumerable) to a specified type and then return a new System.Collections.Generic.IEnumerable<T> collection which contains all the elements of the source sequence cast to the specified type. This method uses deferred execution. The signature of this method is given below.

Parameters:
  1. source: The System.Collections.IEnumerable that contains the elements to be cast to type TResult.
Type Parameters:
  1. TResult: The type to cast the elements of the source.
Exceptions:
  1. It will throw the System.ArgumentNullException when the source is null. 
  2. It will throw the System.InvalidCastException when an element in the source sequence cannot be cast to the specified type TResult.
Returns:
  1. It returns a System.Collections.Generic.IEnumerable contains each element of the source sequence cast to the specified type.
Example 1: Understand LINQ Cast Method in C#:

In the following example, the source sequence contains 3 elements and all these three elements are of type integer. So, all these elements are cast into integers. So, while casting using the Cast method, we need to specify the type to which we want to cast.

Output: 10 20 30

Example 2: Understand LINQ Cast Method in C#:

In the following example, we have created a non-generic (ArrayList) collection that contains integer and string values. Then we are casting that collection to IEnumerable<int> using the Cast<int> method. At runtime, while casting the values, it will throw System.InvalidCastException runtime exception when it tries to cast the string value. 

Example 3: Understand LINQ Cast Method in C#:

In the following example, the source sequence is null. So, when we run the application, it will throw the System.ArgumentNullException.

 

In the next article, I am going to discuss the differences between Cast and OfType Methods in C# with Examples. Here, in this article, I try to explain the need and use of the LINQ Cast Method in C# with Examples. I hope you understood the need, and use of the Cast Method in C#.

Leave a Comment