Puzzling Cast Exception in Enumerable.Cast
An InvalidCastException is encountered when attempting to cast an IEnumerable of integers (ints) to an IEnumerable of long integers (longs) using the Cast operator, as seen below:
using System.Collections.Generic; using System.Linq; namespace InvalidCast { class Program { static void Main(string[] args) { // Initialize a list of ints IEnumerable<int> list = new List<int>() { 1 }; // Attempt to cast the list to longs IEnumerable<long> castedList = list.Cast<long>(); // Attempt to write the first element of the casted list Console.WriteLine(castedList.First()); } } }
Why does this exception occur?
This behavior is unexpected because the Cast operator is intended to perform a safe and reliable conversion. However, this particular case demonstrates a peculiar issue that arose with a modification in the behavior of Cast between .NET 3.5 and .NET 3.5 SP1.
The Root of the Problem
The Cast operator is an extension method defined for IEnumerable (the base interface for collections), not specifically for IEnumerable
As a result, the casting process mimics the following:
int i = 1; object o = i; long l = (long)o;
This code throws the InvalidCastException as it attempts to cast a boxed int to a long, instead of directly casting the int.
Workaround
To resolve this issue, it's necessary to perform the cast explicitly using a lambda expression or a select method, as follows:
// Cast using a lambda expression var castedList = list.Select(i => (long)i); // Cast using a select method var castedList = from long l in list select l;
These approaches explicitly convert each int value to a long, avoiding the boxing/unboxing process and circumventing the InvalidCastException.
The above is the detailed content of Why Does `Enumerable.Cast` Throw an `InvalidCastException` When Casting from `IEnumerable`?. For more information, please follow other related articles on the PHP Chinese website!