Working with a foreach loop is the primary reason to implement the IEnumerable and IEnumerator interfaces. You’ll want one of each of these to work with the loop.
I am going to do an example DateRange class which will implement IEnumerable<DateTime> and will allow us to iterate through a non-existent collection of DateTime objects.
Note: I am aware of the fact that I could achieve the same result with a for loop. I find the foreach loop more readable.
First we need to create a basic DateRange class. A range can be defined as a StartDate and an EndDate, so I’ll start there.
So this DateRange could be useful on its own, but we want to be able to iterate this collection using a foreach. So to start we need to implement the IEnumerable<DateTime> interface.
Notice here that we now need to get the IEnumerator<DateTime> object in the GetEnumerator() method. I jumped the gun a bit and I’ve called a class that doesn’t exist yet. I’ll make another class and implement the required methods for the IEnumerator interface.
These are the handful of methods we implement for the IEnumerator<DateTime> interface. These are all about moving to the next object and getting the current object. Resetting and Disposal of the object are less important, so make sure you read MoveNext and Current.
Keep in mind here that I could have used a collection for this, but I didn’t because I don’t need one. The calculation to get the items was easy enough.