Search⌘ K
AI Features

IEnumerable Interface

Explore how the IEnumerable and IEnumerable<T> interfaces work to enable foreach iteration in C# collections. Understand the role of the IEnumerator interface, its methods, and how to implement these interfaces to create custom iterable collections.

Introduction

Now’s a good time to explore how the foreach loop works. When we iterate using a for loop, we determine how that iteration works. How does the foreach loop know what the first and subsequent items are? How does it determine when there are no more items in the collection?

Know that foreach loops aren’t magic. Types that want to be iterated using a foreach loop must implement the IEnumerable interface:

The IEnumerable<T> interface

Non-generic collections can also be iterated with a foreach loop. Non-generic collections implement the IEnumerable interface, while generic collections utilize the generic collections use the generic ...