#1,117 – foreach Requires IEnumerable Implementation

The foreach statement works on an object that implements IEnumerable<T> or IEnumerable.  It also works on an object whose type has a public GetEnumerator method that returns an IEnumerator<T> or IEnumerator.

Below, we’ve defined a new class that implements IEnumerable<T>.

    public class DogPack : IEnumerable<Dog>
        private List<Dog> thePack;

        public DogPack()
            thePack = new List<Dog>();

        public void Add(Dog d)

        // Remove arbitrary dog
        public void Cull()
            if (thePack.Count == 0)

            if (thePack.Count == 1)
                Random rnd1 = new Random();
                int indRemove = rnd1.Next(thePack.Count);

        // IEnumerable<T> implementation

        public IEnumerator<Dog> GetEnumerator()
            return thePack.GetEnumerator();

        IEnumerator IEnumerable.GetEnumerator()
            return GetEnumerator();

We can now use foreach to iterate on an instance of this class.

            DogPack pack = new DogPack();
            pack.Add(new Dog("Lassie", 8));
            pack.Add(new Dog("Shep", 12));
            pack.Add(new Dog("Kirby", 10));
            pack.Add(new Dog("Jack", 15));

            // Who's left?
            foreach (Dog d in pack)



About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

One Response to #1,117 – foreach Requires IEnumerable Implementation

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 )

Connecting to %s

%d bloggers like this: