Junior — Middle
What ways implement the IEnumerable interface in the programming language?
sobes.tech AI
Answer from AI
In C# language, the IEnumerable interface is implemented by classes and structures that provide a GetEnumerator() method returning an object that implements the IEnumerator interface. This allows iterating over a collection using a foreach loop.
Main ways to implement IEnumerable:
- Manual implementation:
public class MyCollection : IEnumerable
{
private object[] items = {1, 2, 3};
public IEnumerator GetEnumerator()
{
for (int i = 0; i < items.Length; i++)
yield return items[i];
}
}
- Implementation of the generic interface
IEnumerable<T>:
public class MyCollection<T> : IEnumerable<T>
{
private T[] items;
public MyCollection(T[] items) { this.items = items; }
public IEnumerator<T> GetEnumerator()
{
for (int i = 0; i < items.Length; i++)
yield return items[i];
}
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
- Using collections from the standard library that already implement
IEnumerable(e.g.,List<T>,Array).
Thus, the key point is to provide a GetEnumerator() method that returns an enumerator for traversing the collection elements.