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
Release: 2025-01-10 09:57:41
Original
636 people have browsed it

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template