I'm trying to understand the use of the yield keyword in C#, as a queue modelling package I'm using makes extensive use of it.
To demonstrate the use of yield, I am playing around with the following code:
using System;
using System.Collections.Generic;
public class YieldTest
{
static void Main()
{
foreach (int value in ComputePower(2, 5))
{
Console.Write(value);
Console.Write(" ");
}
Console.WriteLine();
}
/**
* Returns an IEnumerable iterator of ints
* suitable for use in a foreach statement
*/
public static IEnumerable<int> ComputePower(int number, int exponent)
{
Console.Write ("Arguments to ComputePower are number: " + number + " exponent: " + exponent + "\n");
int exponentNum = 0;
int numberResult = 1;
while (exponentNum < exponent)
{
numberResult *= number;
exponentNum++;
// yield:
// a) returns back to the calling function (foreach),
// b) updates iterator value (2,4,8,16,32 etc.)
yield return numberResult;
}
}
}
It's pretty evident what the code does, it simply raises 2 to a power using ComputePower
which returns an IEnumerable
. In debugging the code, I see the yield
statement return control to the foreach
loop, and the value
variable is updated with the latest result of the power ie. 2, 4, 8, 16, 32.
Not fully understanding the use of yield
, I expected ComputePower
to be called a number of times as value iterates through ComputePower
and that I would see the "Arguments to ComputePower are "
etc. console write occur 5 times. What actually happens though is it seems the ComputePower
method is called only once. I see the "Arguments to ComputePower.."
string only once per run.
Can somebody explain why this is the case? Does it have something to do with the yield
keyword?