yield break - CSharp Collection

CSharp examples for Collection:Iterator

Introduction

The yield break statement indicates that the iterator block should exit early without returning more elements.

We can modify Foo as follows to demonstrate:

Demo Code

using System;//from   w ww. j a  v a2  s  .  com
using System.Collections.Generic;
class Test
{
   static void Main()
   {
      foreach (string s in Foo(true))
         Console.WriteLine(s);
      }
      static IEnumerable<string> Foo (bool breakEarly)
      {
         yield return "One";
         yield return "Two";
         if (breakEarly)
            yield break;
         yield return "Three";
      }
}

Result


Related Tutorials