Junior — Middle
Can you explain what the GetEnumerator method does in the context of iterating over collections?
sobes.tech AI
Answer from AI
The GetEnumerator method in C# provides an iterator object that allows sequential traversal of a collection's elements. It returns an IEnumerator, which contains methods MoveNext() to move to the next element and the Current property to get the current element. This is the basis for implementing a foreach loop, enabling convenient and safe collection traversal.
Example usage:
List<int> numbers = new List<int> {1, 2, 3};
var enumerator = numbers.GetEnumerator();
while (enumerator.MoveNext())
{
int current = enumerator.Current;
Console.WriteLine(current);
}