IEnumerable
IEnumerable is the promise that something can be walked through one item at a time. Anything that keeps this promise can be used in a foreach loop.
In this page:
Syntax
class ClassName : IEnumerable<type>
{
public IEnumerator<type> GetEnumerator()
{
yield return item;
}
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
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
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Modifying a collection while enumerating it, which throws
InvalidOperationException. - Enumerating a lazy
IEnumerablemultiple times and repeating the work. - Forgetting
yield returnand returning the whole collection at once.
Chapter Summary
- Interfaces define a contract that classes implement, and a class can implement multiple interfaces.
- Default interface methods provide optional implementations.
IComparableandIEnumerableare common interfaces for sorting and iteration.
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: