Junior — Middle
Can you explain what the iterator design pattern is and how it is applied?
sobes.tech AI
Answer from AI
The Iterator design pattern is intended for sequential traversal of collection elements without revealing its internal structure.
Main idea:
- The iterator provides an interface for accessing elements of a collection one by one.
- It allows client code to iterate over elements without knowing how the collection is internally organized.
In C#, the iterator is implemented using the IEnumerator and IEnumerable interfaces. Usually, the yield keyword is used for convenience, which simplifies the creation of iterators.
Example of an iterator in C#:
using System;
using System.Collections;
using System.Collections.Generic;
class MyCollection : IEnumerable<int>
{
private int[] data = {1, 2, 3, 4, 5};
public IEnumerator<int> GetEnumerator()
{
foreach (var item in data)
{
yield return item; // return elements one by one
}
}
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
class Program
{
static void Main()
{
var collection = new MyCollection();
foreach (var item in collection)
{
Console.WriteLine(item);
}
}
}
Here, MyCollection implements IEnumerable<int>, allowing the use of foreach to iterate over elements. The iterator hides the details of data storage and provides a simple way to traverse.