Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can anyone explain IEnumerable and IEnumerator to me? [closed]

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?

like image 338
prodev42 Avatar asked Feb 17 '09 19:02

prodev42


People also ask

What is IEnumerable and IEnumerator?

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.

What does IEnumerable mean?

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.

How does IEnumerator work in C#?

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.

Why is IEnumerable used?

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.


1 Answers

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).

like image 195
Robert Rossney Avatar answered Sep 28 '22 21:09

Robert Rossney