The following throws an InvalidCastException.
IEnumerable<int> list = new List<int>() { 1 }; IEnumerable<long> castedList = list.Cast<long>(); Console.WriteLine(castedList.First());
Why?
I’m using Visual Studio 2008 SP1.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
That’s very odd! There’s a blog post here that describes how the behaviour of
Cast<T>()was changed between .NET 3.5 and .NET 3.5 SP1, but it still doesn’t explain the InvalidCastException, which you even get if you rewrite your code thus:Obviously you can work around it by doing the cast yourself
This works, but it doesn’t explain the error in the first place. I tried casting the list to short and float and those threw the same exception.
Edit
That blog post does explain why it doesn’t work!
Cast<T>()is an extension method onIEnumerablerather thanIEnumerable<T>. That means that by the time each value gets to the point where it’s being cast, it has already been boxed back into a System.Object. In essence it’s trying to do this:This code throws the InvalidCastException you’re getting. If you try to cast an int directly to a long you’re fine, but casting a boxed int back to a long doesn’t work.
Certainly an oddity!