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
yield
keyword inunsafe
blocks of code. - You cannot use the
ref
orout
parameters for methods, operators, or accessors. - You cannot return using the
yield
keyword in atry-catch
block. - You cannot use the
yield
keyword in anonymous methods. - You can use
yield
in atry
block if thetry
block is followed by thefinally
block. - You can use
yield break
in atry-catch
block but not thefinally
block.
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...