CSharp - Iterator yield break

Introduction

The yield break statement returns from the iterator block and stops returning more elements.

You cannot use return statement in an iterator block.

Demo

using System;
using System.Collections.Generic;

class Program//ww  w  .  ja v  a  2s. co  m
{
    static void Main()
    {
        foreach (string s in Test(true))
        {
            Console.WriteLine(s);
        }
        Console.WriteLine("");
        foreach (string s in Test(false))
        {
            Console.WriteLine(s);
        }
    }

    static IEnumerable<string> Test(bool outputAll)
    {
        yield return "One";
        yield return "Two";
        yield return "Three";
        if (outputAll == false)
            yield break;
        yield return "book2s.com";
    }
}

Result