Yield in C#

Introduction

Yield statement appears inside the iterator block. It basically use to provide the value to the enumerator object.

Use

Yield statement is used inside the iterator block to provide value to enumerator object.
Logically it can be used for representing the end of the iteration block.
Basically it can be used in one of the following form

yield return <expression>;
yield break; 
Yield statement may be use as a body of a method ,accessor or operator.
Body of these type of methods define with following restrictions:
  1. Unsafe block should not be there.
  2. Method parameter should not have ref or out.
The one important point about the yield statement is that it can not be used in an anonymous method.
Example
using System;
using System.Collections;
public class List
{
    public static IEnumerable Power(int n, int exp)
    {
        int count = 0;
        int res = 1;
        while (count++ < exp)
        {
            res = res * n;
            yield return res;
        }
    }
    static void Main()
    {
        foreach (int z in Power(2, 8))
        {
            Console.Write("{0}", z);
        }
    }
}
Ebook Download
View all
Learn
View all