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

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

Patricia Arquette
Release: 2025-01-10 10:38:42
Original
741 people have browsed it

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

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());
        }
    }
}
Copy after login

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. This means that when the values are being cast, they have been boxed into objects of type System.Object.

As a result, the casting process mimics the following:

int i = 1;
object o = i;
long l = (long)o;
Copy after login

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

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!

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