Introducing C# 9: Extension GetEnumerator support for foreach loops
Introduction
As you may know, in order to be able to iterate on a collection in C# with the foreach loop the collection must expose a public method GetEnumerator() which doesn’t exist on IEnumerator<T> and IAsyncEnumerator<T> interfaces. C# 9 allows to create an extension method to allow foreach loops on those interfaces. Let’s see in this article how to proceed.
Implement a GetEnumerator extension
It’s quite easy you just have to create an extension method like this:
public static class Extensions
{
public static IEnumerator<T> GetEnumerator<T>(this IEnumerator<T> enumerator) => enumerator;
}
Make sure that extension method is accessible everywhere in your program, and you’ll be able to apply it anywhere.
Usually when you try to iterate with a foreach loop on a collection typed IEnumerator<T> or IAsyncEnumerator<T> you’ll get this message:
Error CS1579 foreach statement cannot operate on variables of type ‘IEnumerator’ // because ‘IEnumerator’ does not contain a public instance or extension definition for ‘GetEnumerator’
With C# 9 and the previous extension (together only) shown above only we can make it work, example:
This is possible because countryEnumerator exposes a public GetEnumerator() method (which is an extension) that is recognized by the foreach statement, example:
Practical isn’t it ? 😉