private IEnumerable GetNames()
{
for (int i = 0; i < 10; i++)
{
yield return "Name:" + i;
}
}
Here, the implementation in case of Yield is simple and straight forward. The GetNames() method iterates through the for loop and returns a value each time it is called. The yield return is different from the return keyword. Where the return keyword stops the execution of the method and returns the control to the calling method, yield return pauses the execution of the method and returns the control to the calling method. The next time when we call the GetNames() method the execution resumes from the point where it left last time.
The yield keyword can take any of the following two forms:
- yield return <expression>;
- yield break;
Where yield return <expression> returns the values to the calling method and paused the execution, yield break ends the execution and permanently returns the control to the calling function.
There are few restrictions while implementing the yield keyword. These are:
- The yield statement can only appear inside an iterator block.
- Unsafe blocks are not allowed.
- Parameters to the method, operator, or accessor cannot be ref or out.
- A yield statement cannot appear in an anonymous method.
- Keep the enumeration code as simple as you can because debugging it afterwards is almost impossible.
Initially Yield may seems like little bit confusing but once you start implementing it you will find it very interesting and powerful.