Possible Duplicates:
Enumerable.Cast<T> extension method fails to cast from int to long, why ?
Puzzling Enumerable.Cast InvalidCastException
Cast/Convert IEnumerable<T> to IEnumerable<U> ?
I m trying to convert an array of integers to an array of doubles (so I can pass it to a function that takes an array of doubles).
The most obvious solution (to me, at least) is to use the Cast extension function for IEnumerable, but it gives me an InvalidCastException, and I don t understand why. My workaround is to use Select instead, but I think Cast looks neater.
Could someone tell me why the Cast method isn t working?
Hopefully the code below illustrates my problem:
namespace ConsoleApplication1
{
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
var intArray = new[] { 1, 2, 3, 4 };
PrintEnumerable(intArray, "intArray: ");
var doubleArrayWorks = intArray.Select(x => (double)x).ToArray();
PrintEnumerable(doubleArrayWorks, "doubleArrayWorks: ");
// Why does this fail??
var doubleArrayDoesntWork = intArray.Cast<double>().ToArray();
PrintEnumerable(doubleArrayDoesntWork, "doubleArrayDoesntWork: ");
// Pause
Console.ReadLine();
}
private static void PrintEnumerable<T>(
IEnumerable<T> toBePrinted, string msgPrefix)
{
Console.WriteLine(
msgPrefix + string.Join(
",", toBePrinted.Select(x => x.ToString()).ToArray()));
}
}
}