|
Why Iterators?
As developers, many would have enjoyed the flexibility offered by foreach statements in C# .earlier to enumerate our enumerable collections using the foreach statements, the Ienumerable interface had to be implemented completely.
In C#2.0 , Iterators have come to the rescue of the developers to make the class enumerable using foreach without implementing much of Ienumerable interface.
Iterators – what it is?
Iterator is a section of code that returns an ordered sequence of values of the same type.
Yield Statement:
A new statement construct called ‘Yield’ has been introduced in C# 2.0 that plays a major role in building simple enumerable collections.
Yield is used in an iterator block to provide value to an enumertor object or to signal the end of an iteration.
Yield takes any of the following two forms.
yield return expression;
yield break;
Iterator Sample:
The common method to implement iterators is to implement the GetEnumerator method in Ienumerable interface.
The sample is as below. |