In .NET 3.5 SP1 Enumerable.Cast
throws InvalidCastException
In .NET 3.5 SP1, a special behavior was observed when using the Enumerable.Cast
method to convert a collection of one type to another type. The following code:
<code class="language-csharp">IEnumerable<int> list = new List<int>() { 1 }; IEnumerable<long> castedList = list.Cast<long>(); Console.WriteLine(castedList.First());</code>
throws InvalidCastException
unexpectedly. This puzzling error also occurs when using LINQ syntax, as shown in the following code:
<code class="language-csharp">var list = new[] { 1 }; var castedList = from long l in list select l; Console.WriteLine(castedList.First());</code>
Reveal hidden behavior
At first it seems confusing why this conversion fails. However, a blog post sheds light on the potential issues. In .NET 3.5 SP1, the Cast<T>()
method was modified to act on IEnumerable
instead of IEnumerable<T>
. Therefore, each element in the collection is boxed into System.Object
before reaching the conversion stage.
Exposed root cause
This fundamental shift leads to a subtle problem. InvalidCastException
is essentially caused by trying the following conversion:
<code class="language-csharp">int i = 1; object o = i; long l = (long)o;</code>
As this code shows, converting int
directly to long
produces the expected results; however, converting a boxed int
to long
fails. This explains why the initial code snippet and its LINQ counterpart don't work as expected.
Looking for solutions
To avoid this exception, the conversion must be performed explicitly:
<code class="language-csharp">var castedList = list.Select(i => (long)i);</code>
This alternative method successfully converts each element without encountering an invalid conversion exception.
This unusual behavior reminds us that some subtle behind-the-scenes mechanisms may affect code execution. To avoid similar pitfalls in the future, it's worth exploring alternatives or handling the conversion explicitly.
The above is the detailed content of Why Does `Enumerable.Cast` Throw an `InvalidCastException` in .NET 3.5 SP1?. For more information, please follow other related articles on the PHP Chinese website!