Export (0) Print
Expand All
3 out of 4 rated this helpful - Rate this topic

Iterators (C# and Visual Basic)

An iterator can be used to step through collections such as lists and arrays.

An iterator method or get accessor performs a custom iteration over a collection. An iterator method uses the Yield (Visual Basic) or yield return (C#) statement to return each element one at a time. When a Yield or yield return statement is reached, the current location in code is remembered. Execution is restarted from that location the next time the iterator function is called.

You consume an iterator from client code by using a For Each…Next (Visual Basic) or foreach (C#) statement or by using a LINQ query.

In the following example, the first iteration of the For Each or foreach loop causes execution to proceed in the SomeNumbers iterator method until the first Yield or yield return statement is reached. This iteration returns a value of 3, and the current location in the iterator method is retained. On the next iteration of the loop, execution in the iterator method continues from where it left off, again stopping when it reaches a Yield or yield return statement. This iteration returns a value of 5, and the current location in the iterator method is again retained. The loop completes when the end of the iterator method is reached.

static void Main()
{
    foreach (int number in SomeNumbers())
    {
        Console.Write(number.ToString() + " ");
    }
    // Output: 3 5 8
    Console.ReadKey();
}

public static System.Collections.IEnumerable SomeNumbers()
{
    yield return 3;
    yield return 5;
    yield return 8;
}

The return type of an iterator method or get accessor can be IEnumerable, IEnumerable<T>, IEnumerator, or IEnumerator<T>.

You can use an Exit Function or Return statement (Visual Basic) or yield break statement (C#) to end the iteration.

A Visual Basic iterator function or get accessor declaration includes an Iterator modifier.

Iterators were introduced in C# in Visual Studio 2005, and were introduced in Visual Basic in Visual Studio 2012.

In this topic

The following example has a single Yield or yield return statement that is inside a For…Next (Visual Basic) or for (C#) loop. In Main, each iteration of the For Each or foreach statement body creates a call to the iterator function, which proceeds to the next Yield or yield return statement.

static void Main()
{
    foreach (int number in EvenSequence(5, 18))
    {
        Console.Write(number.ToString() + " ");
    }
    // Output: 6 8 10 12 14 16 18
    Console.ReadKey();
}

public static System.Collections.Generic.IEnumerable<int>
    EvenSequence(int firstNumber, int lastNumber)
{
    // Yield even numbers in the range. 
    for (int number = firstNumber; number <= lastNumber; number++)
    {
        if (number % 2 == 0)
        {
            yield return number;
        }
    }
}
Note Note

For the remaining examples in the topic, include Imports statements (Visual Basic) or using directives (C#) for the System.Collections and System.Collections.Generic namespaces.

In the following example, the DaysOfTheWeek class implements the IEnumerable interface, which requires a GetEnumerator method. The compiler implicitly calls the GetEnumerator method, which returns an IEnumerator.

The GetEnumerator method returns each string one at a time by using the Yield or yield return statement. In the Visual Basic code, an Iterator modifier is in the function declaration.

static void Main()
{
    DaysOfTheWeek days = new DaysOfTheWeek();

    foreach (string day in days)
    {
        Console.Write(day + " ");
    }
    // Output: Sun Mon Tue Wed Thu Fri Sat
    Console.ReadKey();
}

public class DaysOfTheWeek : IEnumerable
{
    private string[] days = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };

    public IEnumerator GetEnumerator()
    {
        for (int index = 0; index < days.Length; index++)
        {
            // Yield each day of the week. 
            yield return days[index];
        }
    }
}

The following example creates a Zoo class that contains a collection of animals.

The For Each or foreach statement that refers to the class instance (theZoo) implicitly calls the GetEnumerator method. The For Each or foreach statements that refer to the Birds and Mammals properties use the AnimalsForType named iterator method.

static void Main()
{
    Zoo theZoo = new Zoo();

    theZoo.AddMammal("Whale");
    theZoo.AddMammal("Rhinoceros");
    theZoo.AddBird("Penguin");
    theZoo.AddBird("Warbler");

    foreach (string name in theZoo)
    {
        Console.Write(name + " ");
    }
    Console.WriteLine();
    // Output: Whale Rhinoceros Penguin Warbler 

    foreach (string name in theZoo.Birds)
    {
        Console.Write(name + " ");
    }
    Console.WriteLine();
    // Output: Penguin Warbler 

    foreach (string name in theZoo.Mammals)
    {
        Console.Write(name + " ");
    }
    Console.WriteLine();
    // Output: Whale Rhinoceros

    Console.ReadKey();
}

public class Zoo : IEnumerable
{
    // Private members. 
    private List<Animal> animals = new List<Animal>();

    // Public methods. 
    public void AddMammal(string name)
    {
        animals.Add(new Animal { Name = name, Type = Animal.TypeEnum.Mammal });
    }

    public void AddBird(string name)
    {
        animals.Add(new Animal { Name = name, Type = Animal.TypeEnum.Bird });
    }

    public IEnumerator GetEnumerator()
    {
        foreach (Animal theAnimal in animals)
        {
            yield return theAnimal.Name;
        }
    }

    // Public members. 
    public IEnumerable Mammals
    {
        get { return AnimalsForType(Animal.TypeEnum.Mammal); }
    }

    public IEnumerable Birds
    {
        get { return AnimalsForType(Animal.TypeEnum.Bird); }
    }

    // Private methods. 
    private IEnumerable AnimalsForType(Animal.TypeEnum type)
    {
        foreach (Animal theAnimal in animals)
        {
            if (theAnimal.Type == type)
            {
                yield return theAnimal.Name;
            }
        }
    }

    // Private class. 
    private class Animal
    {
        public enum TypeEnum { Bird, Mammal }

        public string Name { get; set; }
        public TypeEnum Type { get; set; }
    }
}

Visual Basic allows a Yield statement in the Try block of a Try...Catch...Finally Statement (Visual Basic). A Try block that has a Yield statement can have Catch blocks, and can have a Finally block.

C# note C# Note

C# allows a yield return statement in the try block of a try-finally statement. A try block that has a yield return statement cannot have any catch blocks.

The following Visual Basic example includes Try, Catch, and Finally blocks in an iterator function. The Finally block in the iterator function executes before the For Each iteration finishes.

Sub Main()
    For Each number As Integer In Test()
        Console.WriteLine(number)
    Next
    Console.WriteLine("For Each is done.")

    ' Output: 
    '  3 
    '  4 
    '  Something happened. Yields are done. 
    '  Finally is called. 
    '  For Each is done.
    Console.ReadKey()
End Sub 

Private Iterator Function Test() As IEnumerable(Of Integer)
    Try
        Yield 3
        Yield 4
        Throw New Exception("Something happened. Yields are done.")
        Yield 5
        Yield 6
    Catch ex As Exception
        Console.WriteLine(ex.Message)
    Finally
        Console.WriteLine("Finally is called.")
    End Try 
End Function

A Yield statement cannot be inside a Catch block or a Finally block.

If the For Each body (instead of the iterator method) throws an exception, a Catch block in the iterator function is not executed, but a Finally block in the iterator function is executed. A Catch block inside an iterator function catches only exceptions that occur inside the iterator function.

In Visual Basic (but not in C#), an anonymous function can be an iterator function. The following example illustrates this.

Dim iterateSequence = Iterator Function() _
                      As IEnumerable(Of Integer)
                          Yield 1
                          Yield 2
                      End Function 

For Each number As Integer In iterateSequence()
    Console.Write(number & " ")
Next 
' Output: 1 2
Console.ReadKey()

The following Visual Basic example has a non-iterator method that validates the arguments. The method returns the result of an anonymous iterator that describes the collection elements.

Sub Main()
    For Each number As Integer In GetSequence(5, 10)
        Console.Write(number & " ")
    Next 
    ' Output: 5 6 7 8 9 10
    Console.ReadKey()
End Sub 

Public Function GetSequence(ByVal low As Integer, ByVal high As Integer) _
As IEnumerable
    ' Validate the arguments. 
    If low < 1 Then 
        Throw New ArgumentException("low is too low")
    End If 
    If high > 140 Then 
        Throw New ArgumentException("high is too high")
    End If 

    ' Return an anonymous iterator function. 
    Dim iterateSequence = Iterator Function() As IEnumerable
                              For index = low To high
                                  Yield index
                              Next 
                          End Function 
    Return iterateSequence()
End Function

If validation is instead inside the iterator function, the validation cannot be performed until the start of the first iteration of the For Each body.

In the following example, the Stack(Of T) generic class implements the IEnumerable<T> generic interface. The Push method assigns values to an array of type T. The GetEnumerator method returns the array values by using the Yield or yield return statement.

In addition to the generic GetEnumerator method, the non-generic GetEnumerator method must also be implemented. This is because IEnumerable<T> inherits from IEnumerable. The non-generic implementation defers to the generic implementation.

The example uses named iterators to support various ways of iterating through the same collection of data. These named iterators are the TopToBottom and BottomToTop properties, and the TopN method.

The BottomToTop property uses an iterator in a get accessor. In the Visual Basic code, the property declaration includes the Iterator keyword.

static void Main()
{
    Stack<int> theStack = new Stack<int>();

    //  Add items to the stack. 
    for (int number = 0; number <= 9; number++)
    {
        theStack.Push(number);
    }

    // Retrieve items from the stack. 
    // foreach is allowed because theStack implements 
    // IEnumerable<int>. 
    foreach (int number in theStack)
    {
        Console.Write("{0} ", number);
    }
    Console.WriteLine();
    // Output: 9 8 7 6 5 4 3 2 1 0 

    // foreach is allowed, because theStack.TopToBottom 
    // returns IEnumerable(Of Integer). 
    foreach (int number in theStack.TopToBottom)
    {
        Console.Write("{0} ", number);
    }
    Console.WriteLine();
    // Output: 9 8 7 6 5 4 3 2 1 0 

    foreach (int number in theStack.BottomToTop)
    {
        Console.Write("{0} ", number);
    }
    Console.WriteLine();
    // Output: 0 1 2 3 4 5 6 7 8 9 

    foreach (int number in theStack.TopN(7))
    {
        Console.Write("{0} ", number);
    }
    Console.WriteLine();
    // Output: 9 8 7 6 5 4 3

    Console.ReadKey();
}

public class Stack<T> : IEnumerable<T>
{
    private T[] values = new T[100];
    private int top = 0;

    public void Push(T t)
    {
        values[top] = t;
        top++;
    }
    public T Pop()
    {
        top--;
        return values[top];
    }

    // This method implements the GetEnumerator method. It allows 
    // an instance of the class to be used in a foreach statement. 
    public IEnumerator<T> GetEnumerator()
    {
        for (int index = top - 1; index >= 0; index--)
        {
            yield return values[index];
        }
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }

    public IEnumerable<T> TopToBottom
    {
        get { return this; }
    }

    public IEnumerable<T> BottomToTop
    {
        get
        {
            for (int index = 0; index <= top - 1; index++)
            {
                yield return values[index];
            }
        }
    }

    public IEnumerable<T> TopN(int itemsFromTop)
    {
        // Return less than itemsFromTop if necessary. 
        int startIndex = itemsFromTop >= top ? 0 : top - itemsFromTop;

        for (int index = top - 1; index >= startIndex; index--)
        {
            yield return values[index];
        }
    }

}

An iterator can occur as a method or get accessor. An iterator cannot occur in an event, instance constructor, static constructor, or static destructor.

An implicit conversion must exist from the expression type in the Yield (Visual Basic) or yield return (C#) statement to the return type of the iterator.

In Visual Basic, an iterator method cannot have any ByRef parameters. In C#, an iterator method cannot have any ref or out parameters.

In Visual Basic, "Yield" is not a reserved word and has special meaning only when it is used in an Iterator method or get accessor. In C#, "yield" is not a reserved word and has special meaning only when it is used before a return or break keyword.

Although you write an iterator as a method, the compiler translates it into a nested class that is, in effect, a state machine. This class keeps track of the position of the iterator as long the For Each...Next or foreach loop in the client code continues.

To see what the compiler does, you can use the Ildasm.exe tool to view the Microsoft intermediate language code that is generated for an iterator method.

When you create an iterator for a class or struct, you do not have to implement the whole IEnumerator interface. When the compiler detects the iterator, it automatically generates the Current, MoveNext, and Dispose methods of the IEnumerator or IEnumerator<T> interface.

On each successive iteration of the For Each…Next or foreach loop (or the direct call to IEnumerator.MoveNext), the next iterator code body resumes after the previous Yield or yield return statement. It then continues to the next Yield or yield return statement until the end of the iterator body is reached, or until an Exit Function or Return statement (Visual Basic) or yield break statement (C#) is encountered.

Iterators do not support the IEnumerator.Reset method. To re-iterate from the start, you must obtain a new iterator.

For additional information, see the Visual Basic Language Specification or the C# Language Specification.

Iterators enable you to maintain the simplicity of a For Each loop when you need to use complex code to populate a list sequence. This can be useful when you want to do the following:

  • Modify the list sequence after the first For Each loop iteration.

  • Avoid fully loading a large list before the first iteration of a For Each loop. An example is a paged fetch to load a batch of table rows. Another example is the EnumerateFiles method, which implements iterators within the .NET Framework.

  • Encapsulate building the list in the iterator. In the iterator method, you can build the list and then yield each result in a loop.

The following C# blogs provide additional information about the use of iterators.

Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft. All rights reserved.