I am using yield and struck somewhere , can anyone explain how yield work
my scenerio is shown below.
public static IEnumerable Power(int number, int exponent)
{
int result = 1;
int counter = 0;
Console.WriteLine("Inside Power - Before While");
while (counter++ < exponent)
{
Console.WriteLine("Inside Power - Inside While");
result = result * number;
yield return result;
//Console.WriteLine("New line added");
}
Console.WriteLine("Inside Power - After While");
}
static void Main(string[] args)
{
foreach (int i in Power(2, 8))
{
Console.WriteLine("{0}", i);
}
}
So the output we are getting here is
Inside Power - Before While
Inside power - Inside While
2
Inside power - Inside While
4
Inside power - Inside While
8
Inside power - Inside While
16
Inside power - Inside While
32
Inside power - Inside While
64
Inside power - Inside While
128
Inside power - Inside While
256
Inside power - AfterWhile
So my question is how the pointer shifts from foreach to Enumerable method while loop and prints and so on.
why whole method is not called and only while loop is executing each time.
The yield return statement is semantically equivalent 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 loop.
This behavior does not exist in the Common Language Runtime. It is implemented by a class generated by the C# compiler. This is then executed and JIT-compiled by the CLR. Yield is a form of syntactic sugar.