.NET Articles

Yield Keyword in C#


If you want to use foreach loop on your class(without deriving from existing collection) then you must implement IEnumerable interface and in order to use IEnumerable interface you must implement interface IEnumerator so basically developer has to write lot of code. Click here to know how to use IEnumerable interface.

The keyword yield reduces the overhead of implementing IEnumerable, IEnumerator interfaces and yield allows iterating group of items using foreach statement. You have to do 2 things to make use of yield feature, they are writing a method that returns IEnumerable interface and write yield statement.

See below example, method GetNames() which has 3 yield statements.

            private static IEnumerable GetNames()
                {
                    yield return "Amar";        
                    yield return "Akbar";
                    yield return "Antony";
                }
        

Use foreach statement as shown below,

        foreach (string item in GetNames())
        {
            Console.WriteLine(item);
        }
        

When GetNames() executed in foreach statement , first time it will fetch the name “Amar” (yield return "Amar";)

In second iteration it will fetch the second name “Akbar” (yield return "Akbar";)

In third iteration it will fetch the third name “Antony” (yield return "Antony ";)

Complete code:
            using System;
            using System.Collections.Generic;

            class Program
            {
                static void Main(string[] args)
                {

                    foreach (string item in GetNames())
                    {
                        Console.WriteLine(item);
                    }
                    Console.ReadLine();
                }
                private static IEnumerable GetNames()
                {
                    yield return "Amar";        
                    yield return "Akbar";
                    yield return "Antony";
                }
            }

        

Output:


        Amar
        Akbar
        Anthony