C# -> How to use IEnumerator and IEnumerable

Introduction

About interfaces in general i wrote in an other post. If you are interested please read first that article and the comeback later on. It is not necessary to read it but if you are new to programming you might get some insights or maybe not. It depends.

Interfaces in C#’s .Net framework are the backbone of that system. Everything relies on them and through that makes programming in C#  a lot easier.

It’s key to understand these so you can move on in c# and tackle the next challenges the language holds for you!

IEnumerator and IEnumerable

IEnumerator and IEnumerable are coupled.  The IEnumerator can live happy without the IEnumerable interface but not the otherway around. IEnumerable depends on the IEnumerator interface.

Let’s first take a look at the two interfaces:

I hope you see why only the IEnumerable interface is coupled to the IEnumerator. IEnumerable only contains ONE function and this function only will enable you how to get an object which has an IEnumerator interface implemented!!!

The consequence is when ever you let an class implementing an IEnumerable interface it has to provide a way to return an object which has implemented an IEnumerator. You can achieve that by letting the class which implements the IEnumerable interfaces also let implementing the IEnumerator interface OR
forward any object which might be an property or field of your class, which already has the IEnumerator interfaces implemented, return in your implementation of the IEnumberable interface.

 

Thats pretty much everything about it. To end this article let me show you a very simple example of a mathematical vector class which implements the IEnumerable containing an array which implements the IEnumerator:

Because we have now a class which implements our desired interface we can use e.g. the foreach loop to take a look on each element of the vector:

This is the beauty about interfaces.

Leave a Reply

Your email address will not be published. Required fields are marked *