Iterators in C#

Started by VelMurugan, Jan 27, 2009, 04:44 PM

Previous topic - Next topic

VelMurugan

Iterators in C#

Iterators allow for a block of code to yield an ordered sequence of values.

Iterators are a mechanism whereby a class can enumerate data using the foreach loop construct. However, iterators are much more flexible than this. You can easily generate a sequence of data returned by the enumerator; it does not have to be hardcoded up front. For example, you could easily write an enumerator that generates the Fibonacci sequence on demand. Another flexible feature of iterators is that you do not have to set a limit on the number of values returned by the iterator, so in this example you could choose when to stop producing the Fibonacci sequence.

Iterators allow you to hand the work of writing this class off to the C# compiler. With Version 2.0 of the C# compiler, the ability for a type to be used by a foreach loop requires much less work.

Source : csharpthegreat