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 www  .java2 s  . c om
{
    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