Home >Backend Development >C++ >Why Does `Enumerable.Cast` Throw an `InvalidCastException` When Casting `IEnumerable` to `IEnumerable`?

Why Does `Enumerable.Cast` Throw an `InvalidCastException` When Casting `IEnumerable` to `IEnumerable`?

Barbara Streisand
Barbara StreisandOriginal
2025-01-10 09:57:41648browse

Why Does `Enumerable.Cast` Throw an `InvalidCastException` When Casting `IEnumerable` to `IEnumerable`?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn