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?
IEnumerable is an interface defining a single method GetEnumerator() that returns an IEnumerator interface. This works for readonly access to a collection that implements that IEnumerable can be used with a foreach statement. IEnumerator has two methods MoveNext and Reset. It also has a property called Current.
IEnumerable is an interface defining a single method GetEnumerator() that returns an IEnumerator interface. It is the base interface for all non-generic collections that can be enumerated. This works for read-only access to a collection that implements that IEnumerable can be used with a foreach statement.
IEnumerable in C# is an interface that defines one method, GetEnumerator which returns an IEnumerator interface. This allows readonly access to a collection then a collection that implements IEnumerable can be used with a for-each statement.
IEnumerable interface is used when we want to iterate among our classes using a foreach loop. The IEnumerable interface has one method, GetEnumerator, that returns an IEnumerator interface that helps us to iterate among the class using the foreach loop.
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()) { 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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With