Iterator Semantics - CSharp Collection

CSharp examples for Collection:Iterator

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 Code

using System;// w  ww.j a v  a2 s. co m
using System.Collections.Generic;

class Test
{
    static void Main()
    {
        foreach (string s in Foo())
            Console.WriteLine(s);         // Prints "One","Two","Three"
    }
    static IEnumerable<string> Foo()
    {
        yield return "One";
        yield return "Two";
        yield return "Three";
    }
}

Result


Related Tutorials