Understand “yield” keyword in C#

Sourav.Kayal
Posted by in C# category on for Beginner level | Points: 250 | Views : 7732 red flag

How to use "yield" keyword in C#

Understand “yield” keyword in C#

In this article we will try to understand “yield” keyword in C#.  The “yield” keyword gives signal to compiler that the block where the “yield” is present contains iterative statement or in simple word, we can use “yield” keyword within iterative statement like with for-each loop.

In the iterative block, the yield keyword is used together with the return keyword to provide a value to the enumerator object.

We can use “yield” keyword to following purpose

To return any enumerator value by writing this code “yield return <expression>”

To return break like “yield break”

We have to keep in mind that yield statement only appears associated with iterative block, which can be implemented as the body of a method or function.

Example of “yield” keyword

Now, we will see one example of “yield” keyword. Here is sample code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
namespace ConsoleApp
{
    class PersonInfo
    {
        List<string> name = new List<string>();
 
        public PersonInfo()
        {
            name.Add("Ram");
            name.Add("shyam");
            name.Add("Jodu");
        }
        public IEnumerable<string> getname()
        {
            yield return name[0];
            yield return name[1];
            yield return name[2];
        }
    }
 
    class Program
    {
        static void Main(string[] args)
        {
            PersonInfo p = new PersonInfo();
            foreach (string name in p.getname())
            {
                Console.WriteLine(name);
            }
            Console.ReadLine();
        }
    }
}

In this example we have created one List within PersonInfo class and then within getname() function, we are sending each name using “yield return name[index]”  code. Within Main() function we are consuming the output of getname() function within for-each loop. As we have discussed earlier, the “yield” keyword comes associated with iterative statement/block.

Here is output


Here is another example of “yield” keyword

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using System.Threading;
namespace ConsoleApp
{
 
    class Program
    {
        static IEnumerable<int> Countdown(DateTime Timelimit)
        {
            for (int i = 1; i <= 5; i++)
            {
                if (DateTime.Now >= Timelimit)
                {
                    yield break;
                }
                yield return i;
            }
        }
        static void Main(string[] args)
        {
            //Create time limit
            DateTime stop = DateTime.Now.AddSeconds(5);
            //Call to Countdown function
            foreach (int i in Countdown(stop))
            {
                Console.WriteLine("Count Value is:  "+ i);
                //Pause for 1 second
                Thread.Sleep(100);
            }
            Console.ReadLine();
        }
    }
}

In this example we have created simple countdown using “yield” keyword. Here is sample output.


 

Restrictions of “yield” keyword.

There are few restrictions to use “yield” keyword.

  • Unsafe block are not allowed.
  • A “yield” return statement cannot be located anywhere inside a try-catch block. We can place “yield” within try if try-catch block contains finally block.
  • We cannot put “yield” keyword within finally block.
Conclusion:-
In this article we discussed on how to use "yield" keyword to iterate collection using for-each loop. Hope you have enjoyed it.


Page copy protected against web site content infringement by Copyscape

About the Author

Sourav.Kayal
Full Name: Sourav Kayal
Member Level: Silver
Member Status: Member,MVP
Member Since: 6/20/2013 2:09:01 AM
Country: India
Read my blog here http://ctrlcvprogrammer.blogspot.in/
http://www.dotnetfunda.com
I am .NET developer working for HelixDNA Technologies,Bangalore in healthcare domain. Like to learn new technology and programming language. Currently working in ASP.NET ,C# and other microsoft technologies.

Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)