Wednesday, February 14, 2018

C# .NET Use of Yield Return Out of the Dating Loop Example

Here's an exampled of using Yield Return out of a loop example combined with a loop example 

As dotNetPerls states about yield statement;
Yield return is similar to a return statement (which passes control flow to the calling method), followed by a "goto" to the yield statement in the next iteration of the foreach.


In case above service goes away.

using System;
using System.Collections.Generic;
//
//Borrow from https://www.dotnetperls.com/yield
//
public class Program
{
 public static IEnumerable<int> ComputePower(int number, int exponent)
    {
        //
        //Return the result with yield out of a loop. Func/Method does not stop on 'return'. Yield return, returns control to continue below.
        //
        yield return 0; 
  
        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 static void Main()
 {
        //
        // Compute powers of two
        //
        int exponent = 0; //no access to interator
        foreach (int value in ComputePower(2, 17))
        {
            
        Console.WriteLine("2^" + (exponent++).ToString() +"="+ value);   
        }
        Console.WriteLine();
 }
}

No comments:

Post a Comment