With yield keyword, the control moves from the caller to source and from the source back to the caller to and fro.
yield statement can be used in two forms:
- yield return <expression>;
- yield break;
Yield return allows you to run custom iteration without temp collection.
Lets take an example to understand in more detail Function to return RandomNumbers using List.
- static IEnumerable < int > GetRandomNumbers(int count)
- {
- Random rand = new Random();
- List < int > ints = new List < int > (count);
- for(int i = 0; i < count; i++)
- {
- ints.Add(rand.Next());
- }
- return ints;
- }
- using System;
- using System.Collections.Generic;
- namespace ConsoleApplication1
- {
- class Program
- {
- static void Main(string[] args)
- {
- foreach(int i in GetRandomNumbers(10))
- Console.WriteLine(i);
- }
- static IEnumerable < int > GetRandomNumbers(int count)
- {
- Random rand = new Random();
- for(int i = 0; i < count; i++)
- {
- yield
- return rand.Next();
- }
- }
- }
- }


Join the conversation! Your thoughts help the community grow.