1

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.

RB.
  • 36,301
  • 12
  • 91
  • 131
user1006544
  • 1,514
  • 2
  • 16
  • 26
  • For a very detailed discussion about this topic, read [this blog post](http://csharpindepth.com/Articles/Chapter6/IteratorBlockImplementation.aspx). – Daniel Hilgarth Feb 13 '13 at 12:48
  • You can think of yield like a "continuation". When you yield a value the actor can get the value, the next time you request a value it'll go back to where it left off in the yielding function and continue as if it never left the function. – devshorts Feb 13 '13 at 12:54
  • Thanx , I have read that post but I want to know about that output . But thanks understand the inside flow – user1006544 Feb 14 '13 at 07:17

1 Answers1

1

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.

Return
Goto

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.

Rajesh Subramanian
  • 6,400
  • 5
  • 29
  • 42