What is Yield Keyword in C#

Updated on: June 10, 2021

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:
  1.     class Program
  2.     {
  3.         static void Main(string[] args)
  4.         {
  5.             foreach (var i in GetData())
  6.             {
  7.                 Console.WriteLine(i.ToString());
  8.             }
  9.             Console.ReadLine();
  10.         }

  11.         static IEnumerable<string> GetData()
  12.         {
  13.             yield return "A";
  14.             yield return "B";
  15.             yield return "C";
  16.             yield return "D";
  17.             yield return "E";
  18.         }
  19.     }
  20.    OUTPUT:
  21.    A
  22.    B
  23.    C
  24.    D
  25.    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