Can anyone explain IEnumerable and IEnumerator to me?
c#, ienumerable, ienumerator
Solution
for example, when to use it over foreach?
You don't use `IEnumerable` "over" `foreach`. Implementing `IEnumerable` makes using `foreach` possible.
When you write code like:
foreach (Foo bar in baz)
{
...
}
it's functionally equivalent to writing:
IEnumerator bat = baz.GetEnumerator();
while (bat.MoveNext())
{
Foo bar = (Foo)bat.Current;
...
}
By "functionally equivalent," I mean that's actually what the compiler turns the code into. You can't use `foreach` on `baz` in this example unless `baz` implements `IEnumerable`.
`IEnumerable` means that `baz` implements the method
IEnumerator GetEnumerator()
The `IEnumerator` object that this method returns must implement the methods
bool MoveNext()
and
Object Current()
The first method advances to the next object in the `IEnumerable` object that created the enumerator, returning `false` 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 implements `IEnumerable`, you can make your class usable in `foreach` statements by implementing `IEnumerable` (and by creating an enumerator class that its new `GetEnumerator` method will return).
Problem
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?