IEnumerable
In this page:
IEnumerable
IEnumerable<T> is the interface that makes a type usable in a foreach loop by exposing a way to get an enumerator over its elements. Arrays, List<T>, and Dictionary<K,V> all implement it. You can implement it yourself on a custom collection type using yield return to produce elements lazily.
Note: yield return inside a method returning IEnumerable<T> builds an iterator without manually implementing IEnumerator.
Example: IEnumerable
using System;
using System.Collections;
using System.Collections.Generic;
class Countdown : IEnumerable<int>
{
private int start;
public Countdown(int start) { this.start = start; }
public IEnumerator<int> GetEnumerator()
{
for (int i = start; i >= 0; i--)
{
yield return i;
}
}
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
class Program
{
static void Main(string[] args)
{
foreach (int n in new Countdown(3))
{
Console.WriteLine(n);
}
}
}
Login to try C/C++/Java/PHP code in the editor
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: