Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c#

How to use Yield Return in C#

Hassan Azhar

Yield Return

The yield return command allows functions to return multiple elements one at a time.

Usage

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 brackets
        foreach (int i in fibb(10)){
          // Here we can process each individual return value
          Console.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 time
            yield return returnVal;

            // Processing done for Fibonacci numbers
            temp = 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.

RELATED TAGS

c#

CONTRIBUTOR

Hassan Azhar
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring