Jerry Nixon @Work: The C# Custom Enumerator; so simple.

Jerry Nixon on Windows

Friday, November 17, 2006

The C# Custom Enumerator; so simple.

Have you heard of the C# custom enumerators? It’s simply a method returning type IEnumerable. Here’s a sample:

public class Animals : List<Animal>
{
public IEnumerable GetMammals()
{
foreach (Animal _Animal in this)
{
if (_Animal.Type == "Mammal")
yield return _Animal;
}
}
}


See that method called GetMammals()? That’s all there is to it. You use the combination of “yield return” to return members of the iterator or “yield break” to stop the processing in the method.


You use it in any old for each statement like this:


foreach (Animal a in List.GetMammals())


It’s so easy – now think further and add parameters to filter or sort and now you see why this exists.