IEnumerator or IEnumerator

IEnumerator or IEnumerator<T> :
If you call the GetEnumerator method of IEnumerable or IEnumerable<T> interface, you get an iterator object as an IEnumerator reference.
An IEnumerator has the MoveNext, Current, and Reset methods

IEnumerator.Reset() – Sets the enumerator to its initial position, which is before the first element in the collection.
IEnumerator.Current – Gets the current element in the collection.
IEnumerator.MoveNext() – Move the enumerator to the next element of the collection.

Enumerators can be used to read the data in the collection/list, but they cannot be used to modify the underlying collection.
Each instance of an Enumerator is a a certain position and can give you that element,an enumerator remains valid as long as the collection remains unchanged.If changes are made to the collection, such as add, edit,delete of elements, the enumerator is invalidated and the next call to the MoveNext or Reset method throws an InvalidOperationException.

Example :

class Program1
{
public static IEnumerable<int> GetEvenNumbers(int[] numbers)
{
foreach (int item in numbers)
{
if (item % 2 == 0)
yield return (item);
}
}

public static void Main()
{
// Static collection.
int[] numbers = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 };

// Return IEnumerable with help of Yield
var evenNumbersCol = GetEvenNumbers(numbers);

// Get IEnumerator from IEnumerable
IEnumerator<int> testNumerator = evenNumbersCol.GetEnumerator();

int sampleNumerator = testNumerator.Current;

Console.WriteLine(“Get first value for Numerator ” + sampleNumerator);

// To advance/get the next value using MoveNext()
if (testNumerator.MoveNext())
{
sampleNumerator = testNumerator.Current;
Console.WriteLine(“Next Even Number = ” + sampleNumerator);
}
// Reset() – Sets the enumerator to its initial position, which is before the first element in the collection.
// testNumerator.Reset();

Console.WriteLine(“After Reset of Numerator ” + testNumerator.Current);

Console.ReadLine();
}
}

Output : –
Get first value for Numerator 0
Next Even Number = 2
After Reset of Numerator 2

As per MSDN
The Reset method is provided for COM interoperability. It does not necessarily need to be implemented; instead, the implementer can simply throw a NotSupportedException.
To verify this please uncomment the 3rd last statement testNumerator.Reset();

Ref – System.Collections.IEnumerator
IEnumerator

Advertisements

One thought on “IEnumerator or IEnumerator”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s