How to use Yield Return

In a yield return statement, expression is evaluated and returned as a value to the enumerator object; expression has to be implicitly convertible to the yield type of the iterator.
The yield statement can only appear inside an iterator block, which can be implemented as the body of a method, operator, or accessor. The body of such methods, operators, or accessors is controlled by the following restrictions:
  • Unsafe blocks are not allowed.
  • Parameters to the method, operator, or accessor cannot be ref or out.
  • A yield return statement cannot be located anywhere inside a try-catch block. It can be located in a try block if the try block is followed by a finally block.
  • A yield break statement may be located in a try block or a catch block but not a finally block.
A yield statement cannot appear in an anonymous method

Sample

 namespace Yield_Return  
{
class Program
{
static void Main(string[] args)
{
// Compute two with the exponent of 30.
foreach (int value in ComputePower(2, 30))
{
Console.Write(value);
Console.Write(" ");
}
Console.WriteLine();
Console.ReadLine();
}
public static IEnumerable ComputePower(int number, int exponent)
{
int exponentNum = 0;
int numberResult = 1;
//
// Continue loop until the exponent count is reached.
//
while (exponentNum < exponent)
{
//
// Multiply the result.
//
numberResult *= number;
exponentNum++;
//
// Return the result with yield.
//
yield return numberResult;
}
}
}
public class Yield {
public IEnumerable GetMergedCount(string[] count, string[] count1)
{
foreach (string item in count)
{
string counts = string.Empty;
foreach (string item1 in count1)
{
if (item1.Equals(item))
{
counts =counts+ item1.ToString();
yield return counts;
}
}
}
}
}
}

Published by Nirbhay

Technology Geek,Blogger,Reviewer

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 )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: