The yield keyword was first introduced in C# 2.0. It returns an object that implements the IEnumerable interface.
The yield keyword is used to build generators of element sequences. A standard case creates a method that generates the sequence you need.
The only limitation here is that the method must return one of the following types: IEnumerable, IEnumerable<T>, IEnumerator or IEnumerator<T> yield can be used in methods, properties, and operators.
See the below code,
static IEnumerable < int > GenerateFibonacciNumbers(int n) {
for (int i = 0, j = 0, k = 1; i < n; i++) {
yield
return j;
int temp = j + k;
j = k;
k = temp;
}
}
static void Main(string[] args) {
foreach(int x in GenerateFibonacciNumbers(10)) {
Console.WriteLine(x);
}
}
yield return j; returns Fibonacci numbers one by one without exiting the “for” loop. The state information is preserved, there is no need of creating an intermediate list or array to hold the fibonacci numbers that need to be generated and returned to the caller. In other words, yield keyword react as a state machine to maintain state information.
The MSDN states: "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."