The following code creates an iterable of all the letters in the alphabet;
var alphabet = Enumerable.Range('a', 26).Select(c => (char)c);
Which works fine. However, the following doesn't work;
var alphabet = Enumerable.Range('a', 26).Cast<char>();
It throws an exception
"System.InvalidCastException: 'Unable to cast object of type 'System.Int32' to type 'System.Char'.'"
You may think this is a duplicate of this or this, but these relate to unboxing objects to a type that is not the original type. In this case, I have an IEnumerable<int>
. Why can't I cast this element by element to IEnumerable<char>
? They are both primitive types, not objects.