c# contextual keywords: yield
yield is a contextual keywords. When it shows in a statement, it means the method or get accessor in which it appears is an iterator. Thus it provides a simple way to define an iterator, rather than a class that implements IEnumerable or IEnumerator.
When you use the
yieldcontextual keyword in a statement, you indicate that the method, operator, orgetaccessor in which it appears is an iterator. Usingyieldto define an iterator removes the need for an explicit extra class (the class that holds the state for an enumeration, see IEnumerator for an example) when you implement the IEnumerable and IEnumerator pattern for a custom collection type.
Grammar
1 | yield return expression; // return an element in the iterator |
Q & A
What’s an iterator?
An iterator means that it can be looped in foreach or LINQ query. In this case, it means the method or get accessor containing yield can be consumed by foreach or LINQ query.
what does yield means in this iterator?
The yield return will return an element in the iterator. During the loop, the iterator use MoveNext to get i (take power method as an example), and the MoveNext stop at the next yield return expression, and the Current property of the iterator is updated as this value, too.
when does the iterator stopped?
- when there’s
yield break - when the method body is end
what’s the requirements to define such iterator?
- The return type must be IEnumerable, IEnumerable, IEnumerator, or IEnumerator.
- The declaration can’t have any in ref or out parameters.
- Don’t use
yieldin Lambda expressions and anonymous methods. - Don’t use
yieldin methods that contain unsafe blocks. For more information, see unsafe. - Don’t use
yield returnin a try-catch block. Ayield returnstatement can be located in the try block of a try-finally statement. yield breakcan be located in a try block or a catch block but not a finally block
examples
yield in method
1 | static void Main(string[] args) |
yield in get accessor
1 | static void Main(string[] args) |