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.

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.

About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

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

  1. Rob Wotherspoon says:

    Andras—Thank you!! The simplest and most straightforward example of this I have found! All the best to you.

    Rob

Leave a comment

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.