Hi,
Can anyone please explain to me what is the difference between IEnumerable & IEnumerator , and how to use them?
Thanks!!!
Hi,
Can anyone please explain to me what is the difference between IEnumerable & IEnumerator , and how to use them?
Thanks!!!
Generally, an IEnumerable
is an object which can be enumerated, such as a list or array. An IEnumerator
is an object that stores the state of the enumeration.
The reason they're not one and the same is that you could have multiple enumerations over the same object at the same time - even in a single-threaded application. For example, consider the following code:
foreach (x in mylist)
{
foreach (y in mylist)
{
if (x.Value == y.Value && x != y)
{
// Found a duplicate value
}
}
}
This would work fine if mylist
is a proper implementation of IEnumerable
, but it would fail if mylist
returned itself as the enumerator.
An IEnumerable
is something that can be enumerated. An IEnumerator
is the means to do that enumeration. So IEnumerable
defines just one method - GetEnumerator
, which returns an instance of IEnumerator
to do the actual legwork...
IEnumerable means something that can be enumerated, IEnumerator is something that enumerates it.
Simplifying it to a simple for-loop:
for (int i=0; i<10;i++)
{
count+=myarray[i];
}
In the example above, i would be IEnumerator, and myarray would be IEnumerable.
IEnumerable
defines an object which contains an aggregation of objects, which can be enumerated.
IEnumerator
is the object which allows the aggregation to be enumerated, and stores the state of the enumeration.
The IEnumerable
interface defines a class which can be enumerated over, i.e. it contains elements which can be accessed through enumeration.
The IEnumerator
interfaces defines a class which can perform enumeration over a sequence of elements.
The distinction is that IEnumerable
means "you can enumerate me", where IEnumerator
performs the task of enumeration.
To elaborate a little more, IEnumerable
exposes a method GetEnumerator
. This method returns an IEnumerator
you can then use to perform the enumerating. Normally you don't deal with this method yourself, because the foreach
keyword handles it for you.
foreach(int element in myList)
{
// Do some work...
}
This code is actually expanded for you by the compiler into this:
IEnumerator enumerator = myList.GetEnumerator();
try
{
while (enumerator.MoveNext())
{
int element = (int)enumerator.Current;
// Do some work...
}
}
finally
{
IDisposable disposable = enumerator as System.IDisposable;
if (disposable != null) disposable.Dispose();
}
As you can see, an IEnumerator
is used here to perform the enumeration through the elements.