Implementing an enumerator for a custom object in .NET C#
July 24, 2015 Leave a comment
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.
Consider the following Guest class:
public class Guest { public string Name { get; set; } public int Age { get; set; } }
Guests can be invited to a Party:
public class Party { private IList<Guest> _guestList; public Party() { _guestList = new List<Guest>(); } public void AddGuest(Guest guest) { _guestList.Add(guest); } }
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.
Here’s the implementation:
public class Party : IEnumerable<Guest> { private IList<Guest> _guestList; public Party() { _guestList = new List<Guest>(); } public void AddGuest(Guest guest) { _guestList.Add(guest); } public IEnumerator<Guest> GetEnumerator() { foreach (Guest guest in _guestList) { yield return guest; } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } }
Let’s test if it works:
Party party = new Party(); party.AddGuest(new Guest() { Age = 25, Name = "John" }); party.AddGuest(new Guest() { Age = 24, Name = "Barbara" }); party.AddGuest(new Guest() { Age = 24, Name = "Phil" }); party.AddGuest(new Guest() { Age = 23, Name = "Fred" }); party.AddGuest(new Guest() { Age = 26, Name = "Hannah" }); party.AddGuest(new Guest() { Age = 27, Name = "Cindy" }); foreach (Guest guest in party) { Debug.WriteLine(guest.Name); }
The code prints the names as expected:
John
Barbara
Phil
Fred
Hannah
Cindy
View all various C# language feature related posts here.