What is the use of yield return in C#?

CsharpServer Side ProgrammingProgramming

Yield keyword helps to do custom stateful iteration over a collection. Meaning when we use yield keyword the control moves back and forth from the caller function to source and vice versa.

Example

 Live Demo

using System;
using System.Collections.Generic;
namespace DemoApplication {
   class Program {
      static List<int> numbersList = new List<int> {
         1, 2, 3, 4, 5
      };
      public static void Main() {
         foreach(int i in RunningTotal()) {
            Console.WriteLine(i);
         }
         Console.ReadLine();
      }
      public static IEnumerable<int> RunningTotal() {
         int runningTotal = 0;
         foreach(int i in numbersList) {
            runningTotal += i;
            yield return (runningTotal);
         }
      }
   }
}

Output

The output of the above program is

1
3
6
10
15

In the above example, in the for each of the main method we are looping through the numbers list of the running total. So whenever the yield return is called the control goes back to main method for each loop and prints the values. Once after printing the value the control again goes to for each of the running total. One thing that needs to noted here is that the previous value is also preserved. So simply, yield keyword effectively creates a lazy enumeration over collection items that can be much more efficient.

raja
Published on 08-Aug-2020 11:32:39
Advertisements