Sunday, January 4, 2009

Iterators in 3.5

Iterators
Iterators are a new feature in C# 2.0. An iterator is a method, get accessor or operator that enables you to support foreach iteration in a class or struct without having to implement the entire IEnumerable interface. Instead, you provide just an iterator, which simply traverses the data structures in your class. When the compiler detects your iterator, it will automatically generate the Current, MoveNext and Dispose methods of the IEnumerable or IEnumerable interface.
Iterators Overview
An iterator is a section of code that returns an ordered sequence of values of the same type.
An iterator can be used as the body of a method, an operator, or a get accessor.
The iterator code uses the yield return statement to return each element in turn. yield break ends the iteration. For more information, see
yield.
Multiple iterators can be implemented on a class. Each iterator must have a unique name just like any class member, and can be invoked by client code in a foreach statement as follows: foreach(int x in SampleClass.Iterator2){}
The return type of an iterator must be IEnumerable,
IEnumerator, IEnumerable, or IEnumerator.
The
yield keyword is used to specify the value, or values, returned. When the yield return statement is reached, the current location is stored. Execution is restarted from this location the next time the iterator is called.

No comments:

Post a Comment

Please leave your comments