What's the rationale behind IEnumerable?

Why do you think Microsoft wants us to go through IEnumerable to get to IEnumerator? Is the presence or absence of a valid IEnumerator cast for a given type enough to determine if the type is enumerable or not?

For example, what happened to the following?

class MyClass : IEnumerator
{
    ...
}

MyClass myObj = new MyClass();

if(myObj as IEnumerator != null)
{
    Console.WriteLine("myObj is enumerable");
}
else
{
    Console.WriteLine("myObj doesn't support enumeration");
}

      

+1


source to share


4 answers


You can have two streams enumerating - each needs its own counter.



IEnumerable.GetEnumerator returns an enumerator that is initially placed before the first element in the collection. If you only had IEnumerator, you will need to remember to reset yourself before using it, even in a single threaded scenario.

+10


source


IEnumerator contains state information needed to perform enumeration, such as array index, etc.

The enumeration state information is NOT part of the enumerated object, so casting will not be powerful enough.



In addition, enum / enumeration separation allows multiple enumerations to be executed concurrently in the same enumerated collection.

+5


source


This is a matter of separation of duties, IEnumerable is a class that can be iterated through IEnumerator is a class that iterates.

+1


source


The accepted answer talks about multithreading, but single-threaded algorithms will be severely limited as well. Keeping reset in mind, the list will not be a problem for foreach to start with, to help you, but suppose you want to compare every item in the list to every other item:

int matchCount = 0;

foreach (var x in myList)
{
    foreach (var y in myList)
    {
        if (x == y)
            matchCount++;
    }
}

matchCount /= 2;

      

If the "current position" was stored inside the list object, both the inner and outer loops will fight in the same place to maintain their current position. Presumably the inner loop will execute once and then the outer loop will exit, dipping past the end of the list.

+1


source







All Articles