How would you implement a custom IEnumerable<T> on your own class using yield return, letting it support foreach?
Short answer
Implement IEnumerable on your class and provide a GetEnumerator() method (using 'yield return' internally) that produces the sequence of elements — this lets instances of your custom class be used directly in a foreach loop, just like a built-in collection.
Advertisement
AModel answer
Implement IEnumerable<T> on your class and provide a GetEnumerator() method (using 'yield return' internally) that produces the sequence of elements — this lets instances of your custom class be used directly in a foreach loop, just like a built-in collection.
public class WeekDays : IEnumerable<string> {
private readonly string[] _days = { "Mon", "Tue", "Wed", "Thu", "Fri" };
public IEnumerator<string> GetEnumerator() {
foreach (var day in _days) yield return day;
}
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
foreach (var day in new WeekDays()) Console.WriteLine(day);Real-world example
Making a custom domain collection class (like a Schedule or Playlist) directly usable in foreach loops, LINQ, and collection initializers.
Likely follow-ups
- Why must you implement BOTH the generic IEnumerable<T>.GetEnumerator() AND the non-generic IEnumerable.GetEnumerator()?
Related topics