The yield return
command allows functions to return multiple elements one at a time.
To return multiple elements using the yield return
command, the return type of a function has to be IEnumerable<type>
or IEnumerator<type>
:
using System;class YieldReturnEnumerable{static void Main(){// foreach collects returned values in i// Function call is in the bracketsforeach (int i in fibb(10)){// Here we can process each individual return valueConsole.Write("{0} ", i);}}// return type is IEnumerable<int>public static System.Collections.Generic.IEnumerable<int> fibb(int num){int returnVal = 1;int temp;int prev = 0;for (int i = 0; i < num; i++){// yield return returns one element at a timeyield return returnVal;// Processing done for Fibonacci numberstemp = returnVal;returnVal = prev + returnVal;prev = temp;}}}
This example demonstrates how an IEnumerable
function uses the yield return
command to return the Fibonacci Sequence. The foreach
loop is used to receive the returned values into variable i
. The function has been called inside the condition parenthesis, ()
, of the foreach
loop.
Free Resources