0Pricing
C# Academy · Lesson

Iterator Methods with yield return

Generate sequences one element at a time.

What Is an Iterator Method?

An iterator method produces a sequence of values one at a time using yield return. The compiler turns it into a state machine, so you do not have to build and manage a list yourself.

Your First yield return

Each yield return hands one value back to the caller and pauses the method. Execution resumes right after that statement on the next iteration.

using System;
using System.Collections.Generic;

public class Program
{
    static IEnumerable<int> FirstThree()
    {
        yield return 1;
        yield return 2;
        yield return 3;
    }

    public static void Main()
    {
        foreach (var n in FirstThree())
            Console.WriteLine(n);
    }
}

All lessons in this course

  1. Iterator Methods with yield return
  2. yield break and Early Termination
  3. Lazy Evaluation Semantics
  4. Custom Enumerables
← Back to C# Academy