C#

what is yield in c sharp


Yield keyword

The functionality this keyword provides is that when iterating a list, we can read an element of the loop, return to the calling code and go back to the loop again at the same point, from where it left the loop and continue processing the records in the loop. So this will be the basic idea behind the example that we will be using.

To demonstrate the use of the yield keyword, we will be creating a list with random numbers from 1-100. Our purpose will be to filter this list to get the numbers greater then 50 (without using any temporary list). So we first create a list and add some elements to it. Next we will create a method that will return an IEnumerator type. This will be the method in which the elements will be iterated and the result will be filtered to get the result list. We will pass the main list to this method and get the results returned from this method. So our code will be like the following:

  class Program
    {
        static void Main(string[] args)
        {
            List<int> num = new List<int>();
            num.Add(12);
            num.Add(45);
            num.Add(34);
            num.Add(55);
            num.Add(13);
            num.Add(77);
            num.Add(85);
            num.Add(17);
            num.Add(67);

            var data = getnum(num);

            foreach(var item in data)
            {
                Console.WriteLine(item);
            }
            Console.ReadKey();
        }
        static IEnumerable<int> getnum(List<int> num)
        {
            foreach(var item in num)
            {
                if (item > 50)
                    yield return item;
            }
        }
    }

So what is actually happening here is that the iteration starts over the list. It checks the first value, 12, that does not matches our selection criteria. So it continues up to fourth element in the same way, that is 55. Here, it encounters the yield statement. So what it does is that it stops the loop iteration and returns to the calling statement again, which is the getnum() function. Then after adding it to the list called _data, it returns to the loop, but this time, it starts the operation from the next element in the list, in other words it starts processing the fifth element, 77. In this way it goes back to the calling code again and returns to process the next element at the sixth position, 85. So it continues to iterate until the loop is completed or a break statement is executed.

yield

Run the application and see the results. We have the desired result without any need of temporary lists.

yield


No comments:

Post a Comment