What is yield in C#.


yield keyword is used for customized iteration in a collection. It is used inside an iterator block which return iterator type. It can not be used directly inside Main method which is void type.

Uses of yield keyword :

  • No need to create temporary list. As it returns value back to caller for every match found.
  • It keeps track of last iterated value. So it does not need to iterate the same value again.

Now lets have an example. We have a list with 20 numbers. But i want to display only even numbers. we can also get even number without using yield keyword. But in this case an extra temp collection need to be created. but with the help of yield keyword we can directly get the even numbers.

static List<int> numbers = new List<int>();
static void NumberList()
{
    for (int i = 1; i<= 20; i++)
    {
        numbers.Add(i);
    }
}

static IEnumerable<int> EvenNumber()
{
    foreach (int i in numbers)
    {
        if (i % 2 == 0) yield return i;
    }
}

static void Main(string[] args)
{
    NumberList();
    IEnumerable<int> EvenNumberList = EvenNumber();
    foreach (int i in EvenNumberList)
    {
        Console.WriteLine(i);
    }
    Console.ReadKey();
}


Output: 2 4 6 8 10 12 14 16 18 20

One thought on “What is yield in C#.

Comments are closed.