Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IEnumerable.Cast() vs casting in IEnumerable.Select()

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.

like image 958
hehewaffles Avatar asked Mar 26 '12 03:03

hehewaffles


1 Answers

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.

like image 128
Andrew Cooper Avatar answered Nov 05 '22 11:11

Andrew Cooper