Since no examples were given, here is one that was helpful to me.
An enumerator is an object that you get when you call .GetEnumerator() on a class or type that implements the IEnumerator interface. When this interface is implemented, you have created all the code necessary for the compiler to enable you to use foreach
to "iterate" over your collection.
Don't get that word 'iterate" confused with iterator though. Both the Enumerator and the iterator allow you to "iterate". Enumerating and iterating are basically the same process, but are implemented differently. Enumerating means you've implemented the IEnumerator interface. Iterating means you've created the iterator construct in your class (demonstrated below), and you are calling foreach
on your class, at which time the compiler automatically creates the enumerator functionality for you.
Also note that you don't have to do squat with your enumerator. You can call MyClass.GetEnumerator()
all day long, and do nothing with it (example:
IEnumerator myEnumeratorThatIWillDoNothingWith = MyClass.GetEnumerator()
).
Note too that your iterator construct in your class only really gets used when you are actually using it, i.e. you've called foreach
on your class.
Here is an iterator example from msdn:
public class DaysOfTheWeek : System.Collections.IEnumerable
{
string[] days = { "Sun", "Mon", "Tue", "Wed", "Thr", "Fri", "Sat" };
//This is the iterator!!!
public System.Collections.IEnumerator GetEnumerator()
{
for (int i = 0; i < days.Length; i++)
{
yield return days[i];
}
}
}
class TestDaysOfTheWeek
{
static void Main()
{
// Create an instance of the collection class
DaysOfTheWeek week = new DaysOfTheWeek();
// Iterate with foreach - this is using the iterator!!! When the compiler
//detects your iterator, it will automatically generate the Current,
//MoveNext and Dispose methods of the IEnumerator or IEnumerator<T> interface
foreach (string day in week)
{
System.Console.Write(day + " ");
}
}
}
// Output: Sun Mon Tue Wed Thr Fri Sat