I don’t believe there’s anything in the framework, but you could easily write one:
IEnumerator<T> Cast<T>(IEnumerator iterator)
{
while (iterator.MoveNext())
{
yield return (T) iterator.Current;
}
}
It’s tempting to just call Enumerable.Cast<T> from LINQ and then call GetEnumerator() on the result – but if your class already implements IEnumerable<T> and T is a value type, that acts as a no-op, so the GetEnumerator() call recurses and throws a StackOverflowException. It’s safe to use return foo.Cast<T>.GetEnumerator(); when foo is definitely a different object (which doesn’t delegate back to this one) but otherwise, you’re probably best off using the code above.