CSharp - Collection Iterator Definition

Introduction

An iterator is a method, property, or indexer that contains one or more yield statements.

An iterator must return one of the following four interfaces:

// Enumerable interfaces
System.Collections.IEnumerable
System.Collections.Generic.IEnumerable<T>

// Enumerator interfaces
System.Collections.IEnumerator
System.Collections.Generic.IEnumerator<T>

Multiple yield statements are permitted.

For example:

Demo

using System;
using System.Collections.Generic;

class Program//from w w  w .  j a v a 2  s.  c o m
{
    static void Main()
    {
        foreach (string s in Test())
        {
            Console.WriteLine(s);
        }

    }

    static IEnumerable<string> Test()
    {
        yield return "One";
        yield return "Two";
        yield return "Three";
        yield return "book2s.com";
    }
}

Result