In newer versions of .net, there are a number of extensions methods which accept IEnumerable<T>
or IEnumerable
. One such method is OfType<TResult>
which returns an enumerable that contains only elements of the original sequence which can be cast to the specified type T
. This method perfectly happily chug away using a non-generic IEnumerable
to process all the items of the original list, regardless of the type of the original list and the destination type. If the original list is an IEnumerable<int>
and TResult
is int
, it will get each item of the original list as a non-generic object
and then cast it, even though it could just use the original IEnumerator<int>
. If the original list is an IEnumerable<int>
and TResult
is StringBuilder
, it will likewise chug through boxing all the items in the original list even though none of them could possibly be cast to the destination type.
How difficult would it be to write a method which would take an IEnumerable<TSrc>
and convert it to an IEnumerable<TResult>
, handling efficiently the cases in which either all items in the original enumeration are guaranteed to appear in the latter, or in which the type of the source enumerator would imply that the latter would be empty (assuming that all variations of IEnumerable
a type supports would return the same sequence of items)? To be sure, one wouldn't terribly often be trying to cast a sequence to the type it already holds, but it's not uncommon to have a generic class with multiple type parameters that will sometimes overlap and sometimes not.