Iterator blocks are called when you want to fetch the data from the Enumerable.
Actually if you call the the function, it will not be called. Rather if you do a foreach on the Enumerable object the function will be called and will return you 10. ;-)
Just change your code a bit as I did:
<br />IEnumerable<int> arr = Documented.GetValuesUpto(10);<br />MessageBox.Show(arr.ToList<int>().Count.ToString());
public static IEnumerable<int> GetValuesUpto(int n)<br />{<br /><br /> for (int ctr = 1; ctr <= n; ctr++)<br /> {<br /><br /> yield return ctr;<br /> }<br /> <br />}
Put a breakpoint in the line
IEnumerable<int> arr = Documented.GetValuesUpto(10);
. and also a breakpoint within
GetValueUpto
block. You will see the function is called when we try to call
ToList
() rather than the actual call to
GetValueUpto
. This is the main advantage of iterator blocks.
[Rose][Rose]