What is Yield Keyword in C#
Followings are the important points on the Yield Keyword of C-Sharp:
- Yield is Contextual Keyword in C#, it is used to indicate a method as an iterator in which yield keyword is used.
- It helps developer to avoid writing another method for holding the state of iteration.
- Yield keyword is used along with "return" & "break", see the following two usage of Yield keyword:
Syntax of Yield in C#:
1. yield return <return Value>;
2. yield break;
- Following is the example of "Yield" keyword:
- class Program
- static void Main(string args)
- foreach (var i in GetData())
- static IEnumerable<string> GetData()
- yield return "A";
- yield return "B";
- yield return "C";
- yield return "D";
- yield return "E";
- From the above example, it returns the value when it reaches "yield return" & it stops the iteration and control goes back to calling method & in the next iteration, it starts from the same place, it left in the last iteration. It continues to do the same till it reaches the end of the loop.
- The return type must be IEnumerable, IEnumerable<T>, IEnumerator, IEnumerator<T>
- Yield return can't be used in try-catch block, it can be used in try block of try-finally statement.
- Yield break can be used in try or catch block, but not in finally block