Implementing an enumerator for a custom object in .NET C#

You can create an enumerator for a custom type by implementing the generic IEnumerable of T interface. Normally you’d do that if you want to create a custom collection that others will be able to iterate over using foreach. However, there’s nothing stopping you from adding an enumerator to any custom type if you feel like it, it’s really simple.

Let’s say that you want to iterate over the guest list. One option is to implement the IEnumerable of T interface in the Party class. You want to return a Guest object in each iteration so the type variable will be Guest. This interface has two methods to implement and they are both called GetEnumerator. You only need to worry about one of them. The second is is there from the old non-generic IEnumerable interface. You can safely call the generic version of the GetEnumerator method from the non-generic one. You also need to be aware of the “yield return” statement.