why the next example throws a System.ArrayTypeMismatchException?
New Int16(){4,5,6}.Cast(of UInt16).ToArray()
I expected that this line returned a UInt16 array containing 4,5 and 6.
Thanks in advance.
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.
This is a bug in
CastorToArray, IMO. The code in this answer is in C#, but hopefully you can see what it’s about 🙂I believe that
Castfirst tries to see if a simple reference conversion will work – i.e. where it can return the same reference back.For example:
Unfortunately, it does this using the CLR rules for compatibility – under which
UInt16[]andInt16[]are compatible. That leads to this happening:Unfortunately if you then try to call
ToArray(), it’s not happy:ToArrayno doubt tries to do some optimisation – which fails in this particular case because the type isn’t what it really expects it to be.I believe the correct behaviour should be for
Castto return a lazy iterator, but for that to fail when it executes later. That’s what happens if you try to go fromInt16toInt32, for example.Now, to get back to what you really want to do: use a
Selectcall instead.Castis only meant to be for unboxing operations and reference type conversions.