Uses of Yield Keyword in c#

Let’s discuss Yield keyword in C#. It is a very powerful keyword. Unfortunately, many of us don’t aware about this keyword or its functionality or uses of Yield keyword. Here I will explain the real use of Yield keyword in C# programming language with some examples.

There are 2 forms of the yield statement.

yield return expression
yield break;

Yield keyword is used in the iterator or foreach loop.  These are the main 2 uses:

  1. It helps to iterate any custom collection without creating any extra class or any temp collections for holding the state for an enumeration.
  2. It helps to do stateful iteration.

yield return:

How yield return is worked with iterators.  When we use yield return statements  (or yield break statements) into a function then it converts it into a state machine. It recorded the state of the function and resumes the execution from that state to the next iteration is called.

Let’s understand the use of yield keyword with an example.  We have created one random integer list and we want to filter even numbers from this random list without creating any temp list.  So we have created one method called GetEvenNumber() and we are passing our random number list to this method. In this method, we check if it is divided by 2 and remainder is 0 then it is even number and returning with yield return keyword.

 class Program
    {
        static void Main(string[] args)
        {
            List<int> randomIntegerList = new List<int>
                                           {
                                               23,84,99,67,92,14,78,43,28
                                           };

            var evenNumberList = GetEvenNumber(randomIntegerList);

            foreach (var number in evenNumberList)
            {
                Console.WriteLine(number);
            }
        }

        public static IEnumerable<int> GetEvenNumber(List<int> randomIntegerList)
        {
            foreach (var number in randomIntegerList)
            {
                if (number % 2 == 0)
                    yield return number;
            }
        }
    }

What is happing in this program? The execution is starting in the GetEvenNumber() method and iterating from the number 23 in forearch loop. It is checking the if condition which is false in this case, so execution will iterator for the next statement for next number i.e. 84. This time ‘if condition’ is true and control will go to yield return statement and now loop iteration will stop and control will pass to the calling statement which is evenNumberList in our case so it will add this ’84’ number to evenNumberList and then return back to the loop but this time execution will start from the number 99 where the execution was left. Loop iteration will not start from the beginning.

Restrictions with ‘yield’ keyword:

  • A yield return statement can not be used inside try-catch block. It can only be used in try block if it is try-finally statement.
  • A yield break statement can be located in a try block or a catch block but not a finally block.
  • If there is an exception occurs in foreach loop body then finally block of the iterator method is executed.
  • We cannot use yield statement inside unsafe code.
  • Yield keyword cannot be used in anonymous methods or lambda expressions.

Some programming scenarios:

Here we are merging two lists with Yield keyword without creating any intermediate collection.

 class Program
    {
        static void Main(string[] args)
        {
            List<string> MarutiCars = new List<string>
                                           {
                                               "WagonR", "Celerio", "Alto K10"
                                           };
            List<string> HyundaiCars = new List<string>
                                           {
                                               "EON", "i10", "i20", "Verna"
                                           };

            var allModels = AllCarModelsEfficientMerge(MarutiCars, HyundaiCars);

            foreach (var model in allModels)
            {
                Console.WriteLine(model);
            }
        }

        static IEnumerable<string> AllCarModelsEfficientMerge(List<string> marutiCars, List<string> hyundaiCars)
        {
            foreach (var m in marutiCars)
                yield return m;

            foreach (var h in hyundaiCars)
                yield return h;
        }
    }

Note: 

The call to AllCarModelsEfficientMerge() doesn’t execute the body of the method. Instead, the call returns an IEnumerable into the “allModels” variable. If you want to debug or execute the body of the method then use ToList(). For example:

 var allModels = AllCarModelsEfficientMerge(MarutiCars, HyundaiCars).ToList();

Written by 

One thought on “Uses of Yield Keyword in c#

Leave a Reply

Your email address will not be published. Required fields are marked *