The foreach
keyword allows you to loop over items in an enumerable collection. Prior to C# 9 this included arrays, dynamic
objects, and objects from classes that implemented the GetEnumerator
method or IEnumerable
interface.
This feature allows foreach
to utilise an GetEnumerator
extension method automatically when available.
Code
C#
void PrintAddress()
{
foreach (var line in address)
Console.WriteLine(line);
}
static class Extension
{
public static IEnumerator<string> GetEnumerator(this Address address)
{
return new AddressLineEnumerator(address);
}
}
C#
void PrintAddress()
{
foreach (var line in new AddressLineEnumeratorAdapter(address))
Console.WriteLine(line);
}
class AddressLineEnumeratorAdapter : IEnumerable<string>
{
readonly Address address;
public AddressLineEnumeratorAdapter(Address address)
{
this.address = address;
}
public IEnumerator<string> GetEnumerator()
{
return new AddressLineEnumerator(address);
}
}