C# features – yield return

In C# we use the iterator pattern to iterate over collections like Dictionary, Queue, ArrayList, List and so on. This collections all implement the IEnumerable interface. For many cases this is a much more convenient way to group objects then using regular arrays.

When you only want to iterate over a subset of a collection, you may use linq to objects to query it, or helper methods that return an IEnumerable instance that contain only the object subset.

If a method returns an IEnumerable, it can return multiple objects by using the yield return statement.

Lets’s look at an Example:

1
2
4
6
8
10

The second example returns a filtered List of objects:

Dan: 20
Mitchell: 25

And yes, the same result can be archived with an simple linq statement:

persons
.Where( person => person.Age >= 18 )
.ToList()
.ForEach( person => Console.WriteLine(person) );

If you’re interested how the C# compiler handles this, have a look at John Skeet’s article “Iterator block implementation details: auto-generated state machines“.