Thursday, March 22, 2012

IEnumerator Interface in Collection classes

Author : Suresh Konjerla

Collections : Collections are enumerable data structures that can be accessed using indexes or keys. Enumerators can be used to read the data in the collection, but they cannot be used to modify the underlying collection. Enumerators are present in System.Collections Name space
The System.Collections namespace:Collections namespace provides a lot of classes, methods and properties to interact with the varying data structures that are supported by it.  The interfaces that are defined in this namespace include:
1)IEnumerable
2)IEnumerator
3)ICollection
4) IList
5) IDictionary
In this post I want to discuss about the IEnumerator  interface:
 
IEnumerator
Methods signatures in the  Enumerator is as follows :

An enumerator is an object that provides a forward, read-only cursor for  a set of items.  The IEnumerable interface has one method called the GetEnumerator() method.  This method returns an object that implements the IEnumerator interface.
IEnumerator provides two abstract methods and a property to access a particular element in a collection. Those are
1)      Reset () - Sets the enumerator to its initial position, which is before the first element in the collection.
2)      MoveNext()-Advances the enumerator to the next element of the collection.
3)      Current - Gets the current element in the collection.



The signature of GetEnumerator() is as follows:
Public IEnumerator GetEnumerator()

{// return IEnumerator of our custom Type

return (IEnumarator)this;

}
Returns an enumerator that iterates through a collection
   Bool MoveNext(): The bool MoveNext() method will help us to move the next instance in the collection. And its objective is to inform the caller whether the current position holds any value or not. If it has, then MoveNext will return true or return false in case there is no value.
Void Reset (): The void Reset () method returns a void type and helps us to position the pointer just before the starting point. Refer to the above figure where I have three instances and the pointer is in the empty position. This reset method will also help us to reset the iteration pointer to the start position from any where.

Public void Reset ()

{

// Setting the pointer to just before the beginning of collection

current = -1;

}

  Public bool MoveNext ()
       {
         // this will increment the counter value
         // and will check whether it is exceeding the actual length of our collection
  
         Return (++current<length)
       }
Current: The object Current property of IEnumerator interface will return an individual element of a given collection. This property is used to return an element of current instance in the collection
 Public object Current ()
{
  Get
    {
      // her”slist “is collection and current is the location of pointer
                    
      Return (slist[current]);
      }
}
The Reset method also brings the enumerator back to this position. At this position, calling the Current property throws an exception. Therefore, you must call the MoveNext method to advance the enumerator to the first element of the collection before reading the value of Current.
An enumerator remains valid as long as the collection remains unchanged. If changes are made to the collection, such as adding, modifying, or deleting elements, the enumerator is irrecoverably invalidated and the next call to MoveNext or Reset throws an InvalidOperationException. If the collection is modified between MoveNext and Current, Current returns the element that it is set to, even if the enumerator is already invalidated.

Example : This program demonstrates how the GetEnumerator() method on the List type works. On a List<int>, GetEnumerator returns a List<int>.Enumerator object. This object implements IEnumerator<int>. We can then write methods that receive IEnumerator<int>.

class Program
    {
        static void Main(string[] args)
        {
            List<int> list = new List<int>();
            list.Add(1);
            list.Add(5);
            list.Add(9);
            List<int>.Enumerator e = list.GetEnumerator();
            Write(e);
            Console.Read();
        }
        static void Write(IEnumerator<int> e)
        {
            while (e.MoveNext())
            {
                int value = e.Current;
                Console.WriteLine(value);
            }
        }
    }

No comments:

Post a Comment