Share via


yield (C# Reference) 

Used in an iterator block to provide a value to the enumerator object or to signal the end of iteration. It takes one of the following forms:

yield return expression;
yield break;

Parameters

expression

Evaluated and returned as a value to the enumerator object. expression has to be implicitly convertible to the yield type of the iterator.

Remarks

The yield statement can only appear inside an iterator block, which might be used as a body of a method, operator, or accessor. The body of such methods, operators, or accessors is controlled by the following restrictions:

  • Unsafe blocks are not allowed.

  • Parameters to the method, operator, or accessor cannot be ref or out.

A yield statement cannot appear in an anonymous method. For more information, see Anonymous Methods (C# Programming Guide).

When used with expression, a yield return statement cannot appear in a catch block or in a try block that has one or more catch clauses. For more information, see Exception Handling Statements (C# Reference).

Example

In the following example, the yield statement is used inside an iterator block, which is the method Power(int number, int power). When the Power method is invoked, it returns an enumerable object that contains the powers of a number. Notice that the return type of the Power method is IEnumerable, an iterator interface type.

// yield-example.cs
using System;
using System.Collections;
public class List
{
    public static IEnumerable Power(int number, int exponent)
    {
        int counter = 0;
        int result = 1;
        while (counter++ < exponent)
        {
            result = result * number;
            yield return result;
        }
    }

    static void Main()
    {
        // Display powers of 2 up to the exponent 8:
        foreach (int i in Power(2, 8))
        {
            Console.Write("{0} ", i);
        }
    }
}

Output

2 4 8 16 32 64 128 256 

C# Language Specification

For more information, see the following sections in the C# Language Specification:

  • 19.3 Iterators

  • 22 Iterators

See Also

Reference

foreach, in (C# Reference)
Using Iterators (C# Programming Guide)

Concepts

C# Programming Guide

Other Resources

C# Reference