Prashant Jadhav

Prashant Jadhav

  • NA
  • 38
  • 14.3k

Iterator and Ienumerator

Jul 30 2014 10:37 AM
hi guys
my question is about enumerator and enumerable implementation . i know there is two ways to make an class collection and making foreach  loop construct use that class object as collection one is by creating enumerator class independently with array which take data from array of an class which is implementing Ienumerable interface with same array type.
for example
 
using System;
using System.Collections;
class ColorEnumerator : IEnumerator
{
string[] _colors;
int _position = -1;
public ColorEnumerator( string[] theColors ) // Constructor
{
_colors = new string[theColors.Length];
for ( int i = 0; i < theColors.Length; i++ )
_colors[i] = theColors[i];
}
public object Current // Implement Current.
{
get
{
if ( _position == -1 )
throw new InvalidOperationException();
if ( _position >= _colors.Length )
throw new InvalidOperationException();
return _colors[_position];
}
}
public bool MoveNext() // Implement MoveNext.
{
if ( _position < _colors.Length - 1 )
{
_position++;
return true;
}
else
return false;
}
public void Reset() // Implement Reset.
{
_position = -1;
}
}
 
class Spectrum : IEnumerable
{
string[] Colors = { "violet", "blue", "cyan", "green", "yellow", "orange", "red" };
public IEnumerator GetEnumerator()
{
return new ColorEnumerator( Colors );
}
}
class Program
{
static void Main()
{
Spectrum spectrum = new Spectrum();
foreach ( string color in spectrum )
Console.WriteLine( color );
}
}
 
 
here enumerator class(ColorEnumerator)  has implemented all those method which are members of Ienumerator Interface
now foreach construct will use enumerator class implemented by  ColorEnumerator 
bye using GetEnumerator() method of spectrum class as shown below
 
 
but my problem is that since this example give me clear understanding of  how foreach is handling value of spectrum collection
but when we use iterator for implementing enumerator automatically how CLR create that enumerator class which require to manipulate elements in collection because in an book i read that The compiler takes iterator description of how to enumerate the items and uses it to build an
enumerator class, including all the required method and property implementations. The resulting class
is nested inside the class where the iterator is declared.
class zoo:Ienumerable
{
 string[] animal=new string[4];
public Ienumarator<string> GetEnumerator()
{
foreach(string anim in animal) 
yield return anim; 
now how the zoo class will contain Ienumerator<string> class in it as written above  so that  Ienumerator<string> class will contain move next,reset and current function to manipulate zoo collection please give me example in coding.
thank you 
 
 

Answers (1)