I have following code snippet in c#
List<int> list = new List<int>() { 1, 23, 5, 3, 423, 3 };
var query = list.Cast<double>().Select(d => d);
try
{
foreach (var item in query)
{
Console.WriteLine(item);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
It’s compile perfectly,but when i am executing this I am getting exception.
Because you’re typecasting from an int to double, it’s not a conversion it’s a type cast and this is somewhat different from when you cast int to double in the general case.
The
Cast<T>extension method uses the IL instructionunbox.anyWhile a C# cast like this
Actually results in the IL instruction
Fundamentally unboxing an type as a different type is wrong and that’s why you get the exception.
This question has the same answer and also links to a blog post by Eric Lippert.