Hi,
Try this,
Method with IEnumerable return type is not executed when expected
See the following short sample:
class Program
{
static void Main(string[] args)
{
Items<int> items = new Items<int>();
items.GetItems();
}
}
public class Items<T>
{
public IEnumerable<T> GetItems()
{
Console.WriteLine("GetItems called");
yield break;
}
}
The evident question would be after seeing this code : What is written to the console?
The first answer would be “GetItems called” but that’s the wrong answer. The right answer is nothing because the enumerator is not executed by the .NET framework until its first element is referenced. So in the above code the GetItems method is never executed.
However if we start to iterate through the items, the enumerator is called as we would expect. To see it, just replace the item.GetItems() line with a foreach, like foreach (var i in items.GetItems()) {}
Hope it helps.