C# Enumerator

C# Enumerator
An Enumerator is an object used to iterate over a collection. Unlike using a for-each loop, when using an Enumerator you are responsible for checking when you have iterated over the entire collection.



For this tutorial we will use the following list as a data structure:
 List<int> items = new List() {1, 3, 2, 4, 6};
 

To get an Enumerator we use the GetEnumerator method as follows:

 var it = items.GetEnumerator();
 

You can think of it as being to a pointer to one item in a collection. Originally when you create the Enumerator the pointer is pointing to just before the first item of the collection so you will have to call MoveNext to move the pointer to the first item.

Example:

 it.MoveNext();
 

At this point it now points to the first item in the list (1). To access the current item in the list we make use of the Current property.
For example:

 var next = it.Current;
 

Iterating over the entire collection

To iterate over the entire collection we have two options, one option is to use a loop and check if it.Current is null. When it.Current returns null we know we have traversed the entire collection and this is when we stop the loop. There is one small technicality here though is when using an array of objects we might want to have certain values being null. Then our loop using it.Current != null as the test is not valid.

Consider this code:

 it = items.GetEnumerator();
 items
.MoveNext();
 
while (it.Current != null) {
           
Console.WriteLine(it.Current);
           it
.MoveNext();
 
}
 

The output of this will be:

Quote
1
3
2

4
6

As mentioned previously if the list contains a null entry then this code will not work correctly. So in this case we should use MoveNext() as the condition. This function returns false when we have passed all items in the collection and true otherwise. For this reason, it is usually safer to always make use of it.MoveNext() and in the body of the loop check if it.Current is null before processing.
Example:

  while (it.MoveNext()){
         
if(it.Current == null) continue;
       
Console.WriteLine(it.Current);
}

If the current item is null we use continue which goes to the next iteration. On each iteration MoveNext is called which moves the pointer to the next element in the collection and returns true. It returns false when we have seen every element and the loop stops. 

No comments:

Post a Comment