The Yield Keyword in C#

This tutorial will discuss the uses of the yield keyword in C#.

the yield Keyword in C

The yield keyword is a contextual keyword in C#. It is used with the return keyword to specify that the method it is used in is an iterator. The best use of the yield keyword is when we are iterating through a list. With the yield keyword, we can loop through a list and return an element from the list to the calling function and then return to the loop and start it from the next index. The yield keyword returns an object of the IEnumerator class. So, the return type of the function using the yield keyword needs to be IEnumerator. The following code example shows us how we can use the yield keyword in C#.

using System;
using System.Collections.Generic;

namespace yield_keyword
{
    class Program
    {
        static IEnumerable<string> Strings()
        {
            List<string> Values = new List<string> { "value1", "value2", "value3", "value4" };
            foreach(var val in Values)
            {
                yield return val;
            }
        }
        static void Main(string[] args)
        {
            foreach (var i in Strings())
            {
                Console.WriteLine(i);
            }
        }
    }
}

Output:

value1
value2
value3
value4

We created a function Strings() that returns elements of the list of strings Values with the yield keyword in C#. The yield keyword grabs a value from the Values list, returns it to the calling function, and then continues the loop from the next iteration if the Strings() function is invoked again.

Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - Csharp Keyword

  • Java Final Equivalent Keyword in C#
  • The Nameof Expression in C#