Example of Implementing IEnumerable and IEnumerator in C#

In the .NET Framework, there are two interfaces designed to allow you to iterate easily over collections of objects as you would typically do in a for loop. Many classes in the .NET Framework have implemented these interfaces and do their work behind the scenes so you don’t have to worry about how it is done. However, sometimes you want to have the control to do this yourself.

Maybe you have the need to create a custom class that holds a collection of objects, and you want to be able to iterate over them. It’s pretty straightforward to do this in C# or VB.NET. You have to implement two interfaces called IEnumerable and IEnumerator. Below is a trivial example (because it’s already possible to do this with the List class) that illustrates how you would go about implementing these to iterate over a collection of string objects:

using System;
using System.Collections.Generic;
using System.Collections;
 
namespace Demo
{
	public class TestOverride : IEnumerable<string>
	{
                private List<string> _values;
 
                public TestOverride(List<string> values)
                {
                    _values = values;
                }
 
		public IEnumerator<string> GetEnumerator()
		{
		    return new TestOverrideEnumerator(_values);
		}
 
		IEnumerator IEnumerable.GetEnumerator()
		{
			return GetEnumerator();
		}
 
		protected class TestOverrideEnumerator : IEnumerator<string>
		{
			private List<string> _values;
			private int _currentIndex;
 
			public TestOverrideEnumerator(List<string> values)
			{
				_values = new List<string>(values); 
				Reset();
			}
 
			public string Current
			{
				get { return _values[_currentIndex]; }
			}
 
			public void Dispose() {}
 
			object IEnumerator.Current
			{
				get { return Current; }
			}
 
			public bool MoveNext()
			{
				_currentIndex++;
				return _currentIndex < _values.Count;
			}
 
			public void Reset()
			{
				_currentIndex = -1;
			}
		}
	}
}

I’m sure there’s a better way to do this, but it should help you get started. Note that you have to implement both classes and that the most work is done in the class that implements IEnumerator. Also note that you can use generics (in this case force it to iterate only over string objects).

You would invoke this functionality this way:

List<string> collection = new List<string>();
collection.Add("abc");
collection.Add("def");
collection.Add("ghi");
 
TestOverride collectionWrapper = new TestOverride(collection);
 
foreach (string x in collectionWrapper)
    Console.Out.WriteLine(x);

Leave a Reply