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.

3
  • For a very detailed discussion about this topic, read this blog post. Commented Feb 13, 2013 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. Commented Feb 13, 2013 at 12:54
  • Thanx , I have read that post but I want to know about that output . But thanks understand the inside flow Commented Feb 14, 2013 at 7:17

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.