Exploring the yield keyword
The yield keyword is contextual and is used with iterators. The following are the two ways to use the yield keyword:
yield return <expression>;: This returns the value of the expression.yield break;: This will exit from the iteration
When using the yield keyword, there are some restrictions to be aware of. These are as follows:
- You cannot use the
yieldkeyword inunsafeblocks of code. - You cannot use the
reforoutparameters for methods, operators, or accessors. - You cannot return using the
yieldkeyword in atry-catchblock. - You cannot use the
yieldkeyword in anonymous methods. - You can use
yieldin atryblock if thetryblock is followed by thefinallyblock. - You can use
yield breakin atry-catchblock but not thefinallyblock.
In this section, we are going to add a class that shows the yield keyword in action. Then, we will benchmark two ways to return an IEnumerable<long> consisting...