Look at the source code of Cast
. When you use Cast
you are iterating the collection as an array of object
, and then it is converted to the desidered type. So the generated code (for the Cast
part) for the code you post is:
foreach (object item in text)
{
yield return (int)item;
}
Of course, this will generate an exception as documented here (link provided by Rawling in the comments, thank you).
To reproduce this you can try this code (you will get the same error):
var myChar = 'c';
object myObject = myChar;
int myInt = (int)myObject; // Exception here
A possibile solution
Disclaimer: tested only with the given example and of course really slow).
You could make your own Cast
method using Convert.ChangeType
.
public static class IEnumerableExtensions
{
public static IEnumerable<TResult> MyCast<TResult>(this IEnumerable source)
{
var type = typeof(TResult);
foreach (var item in source)
{
yield return (TResult)Convert.ChangeType(item, type);
}
}
}
Then you can use it as you would do with Cast
.
var c1 = text.MyCast<int>();