yield keyword is used to define an iterator with maintaining state of data during iteration.
We use a yield return statement to return each element one at a time.
We consume an iterator method by using a foreach statement or LINQ query. Each iteration of the foreach loop calls the iterator method. When a yield return statement is reached in the iterator method, expression is returned, and the current location in code is retained. Execution is restarted from that location the next time that the iterator function is called.
yield preserves returned variable value during iteration.
Limitation: yield can't be use in try-catch block
Source Code:
Result:
We use a yield return statement to return each element one at a time.
We consume an iterator method by using a foreach statement or LINQ query. Each iteration of the foreach loop calls the iterator method. When a yield return statement is reached in the iterator method, expression is returned, and the current location in code is retained. Execution is restarted from that location the next time that the iterator function is called.
yield preserves returned variable value during iteration.
Limitation: yield can't be use in try-catch block
Source Code:
class Program
{
static void Main(string[] args)
{
foreach (int res in power(3, 6))
{
Console.WriteLine("{0} ", res);
}
Console.ReadLine();
}
private static IEnumerable<int> power(int number, int exponent)
{
int result = 1;
for (int i = 0; i < exponent; i++)
{
result = result * number;
yield return result;
}
}
}


No comments:
Post a Comment