The yield statement allows us to populate an instance implementing IEnumerable. Modifying the MSDN code sample for yield, this is an example without using yield:
public static List<int> Power(int number, int exponent)
{
int counter = 0;
int result = 1;
var list = new List<int>();
while(counter++ < exponent)
{
result = result * number;
list.Add(result);
}
return list;
}
Without yield we are forced to choose a class implementing IEnumerable. In the example above we must use List<int>. Now the example using yield:
public static IEnumerable<int> Power(int number, int exponent)
{
int counter = 0;
int result = 1;
while(counter++ < exponent)
{
result = result * number;
yield return result;
}
}
The opinion here is that yield is harder to understand when the purpose of IEnumerable is not understood. One reminder is that IEnumerable requires sequential access through, say, the foreach loop. The IEnumerable interface does not define a member for random-access.
More information: “Using C# Yield for Readability and Performance”
http://www.ytechie.com/2009/02/
using-c-yield-for-readability-and-performance.html