What is the use of yield keyword in C#?

 Posted by Ddd on 2/8/2011 | Category: C# Interview questions | Views: 9086 | Points: 40
Answer:

Yield keyword is used in an iterator block to calculate the value for the enumerator object.

An iterator is a method,
get accessor, or operator that allows us to use foreach loop on object references of user-defined classes.

yield keyword can be used as:

1)yield return <expression>;
or
2)yield break;


code snippet

using System;

//This namespace provides the IEnumerator interface
using System.Collections;
public class demo
{
//GetEnumerator method of IEnumerable interface creates the iterator
public IEnumerator GetEnumerator()
{
for (int i = 1; i <=5; i++)
{
yield return i;
}
}


static void Main()
{

demo t=new demo();

//foreach loop calls the GetEnumerator method
foreach (int i in t)
{
Console.WriteLine(i);
}
}
}


output:

1
2
3
4
5


| Alert Moderator 

Comments or Responses

Posted by: Kishork80 on: 2/9/2011 | Points: 10
In addition to that 'yield' defers and also saves the current evaluation of expression till the next iteration. That means teh values won't be read untill unless the statement is executed next time again.
Posted by: Ddd on: 2/9/2011 | Points: 10
Yes, that's correct. Thanks.

Login to post response