Suppose I have an IEnumerable<int>
and I want these to be converted into their ASCII-equivalent characters.
For a single integer, it would just be (char)i
, so there's always collection.Select(i => (char)i)
, but I thought it would be a tad cleaner to use collection.Cast()
.
Can anyone explain why I get an InvalidCastException
when I use collection.Cast<char>()
but not with collection.Select(i => (char)i)
?
Edit: Interestingly enough, when I call collection.OfType<char>()
I get an empty set.
The Cast<T>
and OfType<T>
methods only perform reference and unboxing conversions. So they can't convert one value type to another value type.
The methods operate on the non-generic IEnumerable
interface, so they're essentially converting from IEnumerable<object>
to IEnumerable<T>
. So, the reason you can't use Cast<T>
to convert from IEnumerable<int>
to IEnumerable<char>
is that same reason that you can't cast a boxed int
to a char
.
Essentially, Cast<char>
in your example fails because the following fails:
object ascii = 65;
char ch = (char)ascii; <- InvalidCastException
See Jon Skeet's excellent EduLinq post for more details.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With