Can anyone explain IEnumerable and IEnumerator to me?
for example, when to use it over foreach? what's the difference between IEnumerable and IEnumerator? Why do we need to use it?
Can anyone explain IEnumerable and IEnumerator to me?
for example, when to use it over foreach? what's the difference between IEnumerable and IEnumerator? Why do we need to use it?
Implementing
IEnumerable
essentially means that the object can be iterated over. This doesn't necessarily mean it is an array as there are certain lists that can't be indexed but you can enumerate them.IEnumerator
is the actual object used to perform the iterations. It controls moving from one object to the next in the list.Most of the time,
IEnumerable
&IEnumerator
are used transparently as part of aforeach
loop.Explanation via Analogy + Code Walkthrough
First an explanation without code, then I'll add it in later.
Let's say you are running an airline company. And in each plane you want to know information about the passengers flying in the plane. Basically you want to be able to "traverse" the plane. In other words, you want to be able to start at the front seat, and to then work your way towards the back of the plane, asking passengers some information: who they are, where they are from etc. An aeroplane can only do this, if it is:
Why these requirements? Because that's what the interface requires.
If this is information overload, all you need to know is that you want to be able to ask each passenger in the plane some questions, starting from the first and making your way to the last.
What does countable mean?
If an airline is "countable", this means that there MUST be a flight attendant present on the plane, who's sole job is to count - and this flight attendant MUST count in a very specific manner:
Counting Procedures
The captain of the airline wants a report on every passenger as and when they are investigated or counted. So after speaking to the person in the first seat, the flight-attendant/counter then reports to the captain, and when the report is given, the counter remembers his/her exact position in the aisle and continues counting right where he/she left off.
In this manner the captain is always able to have information on the current person being investigated. That way, if he finds out that this individual likes Manchester City, then he can give that passenger preferential treatment etc.
Let's tie this with the IEnumerables
An enumerable is just a collection of passengers on a plane. The Civil Aviation Law - these are basically the rules which all IEnumerables must follow. Everytime the airline attendant goes to the captain with the passeger information, we are basically 'yielding' the passenger to the captain. The captain can basically do whatever he wants with the passenger - except rearranging the passengers on the plane. In this case, they are given preferential treatment if they follow Manchester City (ugh!)
Summary
In other words, something is countable if it has a counter. And counter must (basically): (i) remember its place (state), (ii) be able to move next, (iii) and know about the current person he is dealing with.
Enumerable is just a fancy word for "countable". In other words, an enumerable allows you to 'enumerate' (i.e. count).
Implementing IEnumerable enables you to get an IEnumerator for a list.
IEnumerator allows foreach style sequential access to the items in the list, using the yield keyword.
Before foreach implementation (in Java 1.4, for example), the way to iterate a list was to get an enumerator from the list, then ask it for the "next" item in the list, for as long as the value returned as the next item is not null. Foreach simply does that implicitly as a language feature, in the same way that lock() implements the Monitor class behind the scenes.
I expect foreach works on lists because they implement IEnumerable.
You don't use
IEnumerable
"over"foreach
. ImplementingIEnumerable
makes usingforeach
possible.When you write code like:
it's functionally equivalent to writing:
By "functionally equivalent," I mean that's actually what the compiler turns the code into. You can't use
foreach
onbaz
in this example unlessbaz
implementsIEnumerable
.IEnumerable
means thatbaz
implements the methodThe
IEnumerator
object that this method returns must implement the methodsand
The first method advances to the next object in the
IEnumerable
object that created the enumerator, returningfalse
if it's done, and the second returns the current object.Anything in .Net that you can iterate over implements
IEnumerable
. If you're building your own class, and it doesn't already inherit from a class that implementsIEnumerable
, you can make your class usable inforeach
statements by implementingIEnumerable
(and by creating an enumerator class that its newGetEnumerator
method will return).IEnumerable implements GetEnumerator. When called, that method will return an IEnumerator which implements MoveNext, Reset and Current.
Thus when your class implements IEnumerable, you are saying that you can call a method (GetEnumerator) and get a new object returned (an IEnumerator) you can use in a loop such as foreach.