How Yield keyword works in C#

Yield in C# , can use with the return statement to build a collection of returns. For example , I have a method that we need to return a collection of integers in a lazy manner and expose it through an IEnumerable interface. Based on the value produce with the yield return , consumer can write some logic based on their need.

In the below example you can see I have a method ReturnSomeIntegers() , which return 1 to 10 by iterate using for loop with yield keyword and also two more yield return with 20 and 30 respectively.

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

YieldDemo();
Console.ReadKey();

}
static void YieldDemo()
{
foreach ( int n in ReturnSomeIntegers())
{
if (n == 20)
{
Console.WriteLine("From Yield Return Two - " + n);
}
else if (n == 30)
{
Console.WriteLine("From Yield Return Three - " + n);
}
else
{
Console.WriteLine("From Yield Return One - " + n);
}
}
}
private static IEnumerable ReturnSomeIntegers()
{
for(int i = 1; i <= 10; i++)
{
yield return i;
}
yield return 20;
yield return 30;
}
}

Whenever ReturnSomeIntegers() method return a single value , the execution will switchback to YieldDemo() for each method and print the value based on the condition.

In Computer Science this is known as Continuation
https://en.wikipedia.org/wiki/Continuation

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s