Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IEnumerable & IEnumerator

Tags:

.net

interface

Can anyone please explain to me what is the difference between IEnumerable & IEnumerator , and how to use them?

Thanks!!!

like image 823
Zabo Avatar asked Apr 14 '10 08:04

Zabo


1 Answers

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.

like image 115
EMP Avatar answered Nov 15 '22 11:11

EMP