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.

Advertisements

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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

ultimatemindsettoday

A great WordPress.com site

Elliot Balynn's Blog

A directory of wonderful thoughts

Robin Sedlaczek's Blog

Developer on Microsoft Technologies

HarsH ReaLiTy

A Good Blog is Hard to Find

Softwarearchitektur in der Praxis

Wissenswertes zu Webentwicklung, Domain-Driven Design und Microservices

the software architecture

thoughts, ideas, diagrams,enterprise code, design pattern , solution designs

Technology Talks

on Microsoft technologies, Web, Android and others

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

Anything around ASP.NET MVC,WEB API, WCF, Entity Framework & AngularJS

Cyber Matters

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

Guru N Guns's

OneSolution To dOTnET.

Johnny Zraiby

Measuring programming progress by lines of code is like measuring aircraft building progress by weight.

%d bloggers like this: