Understanding Enumerable.Cast
and InvalidCastException
in C#
A common C# error occurs when using Enumerable.Cast<T>
to convert an IEnumerable<int>
to an IEnumerable<long>
. The unexpected InvalidCastException
arises despite the apparent type compatibility.
The reason lies in how Enumerable.Cast<T>
functions. It's not a specialized method for generic collections; it operates at the IEnumerable
level, working with unboxed values.
Therefore, when casting elements from an IEnumerable<int>
, each int
is already boxed as an object
. Attempting to cast a boxed int
to a long
directly fails, resulting in the InvalidCastException
.
The solution is to explicitly cast each element within a query:
<code class="language-csharp">var castedList = list.Select(i => (long)i);</code>
This Select
method performs the conversion from int
to long
for each item, avoiding the boxing issue. This direct cast circumvents the limitations of Enumerable.Cast<T>
when dealing with value type conversions.
The above is the detailed content of Why Does `Enumerable.Cast` Throw an `InvalidCastException` When Casting `IEnumerable` to `IEnumerable`?. For more information, please follow other related articles on the PHP Chinese website!