IEnumerator
A simple iteration over a collection is supported by IEnumerator. It is an interface and is the base interface for all enumerators. IEnumerator performs iteration but cannot be used with foreach loop ,it is only to be used with while loop.
Syntax of IEnumerator:
public interface IEnumerator
Property of IEnumerator:
Current: The current element in the collection which is being iterated is obtained by this property.
object Current {get;}
Public methods of IEnumerator:
MoveNext: It make the enumerator to advance to next element in the collection which is being iterated.
bool MoveNext();
Reset: Reset method initializes the enumerator to its initial position, which is before the first element in the collection.
void Reset();
Example of IEnumerator:
Consider a list in C#:
List<int> ages = new List<int>();
ages.Add(10);
ages.Add(20);
ages.Add(30);
ages.Add(40);
ages.Add(50);
Using IEnumerator with above list:
IEnumerator<int> age_IEnumerator = ages.GetEnumerator();
while (age_IEnumerator.MoveNext())
{
Console.WriteLine(age_IEnumerator.Current);
}
0 Comment(s)