Yield has two great uses
It helps to provide custom iteration with out creating temp collections.
It helps to do stateful iteration
Iteration. It creates a state machine "under the covers" that remembers where you were on each additional cycle of the function and picks up from there.
e.g.
private static IEnumerable<string> GetIdList(DateTime startTime, DateTime endTime)
{
var collectionList = new List<string>(); for (var dateTime = new DateTime(startTime.Year, startTime.Month, 1); dateTime <= endTime; dateTime = dateTime.AddMonths(1))
{
collectionList.Add(dateTime.ToString("d"));
} return collectionList;
}
could be writen as:
private static IEnumerable<string> GetIdList(DateTime startTime, DateTime endTime)
{
for (var dateTime = new DateTime(startTime.Year, startTime.Month, 1); dateTime <= endTime; dateTime = dateTime.AddMonths(1))
{
yield return collectionList.Add(dateTime.ToString("d"));
}
}
- It helps to provide custom iteration with out creating temp collections.
It helps to do stateful iteration.
- In order to explain the above two points more demonstratively, I have created a simple video and the link for same is here: http://www.youtube.com/watch?v=4fju3xcm21M