IEnumerable: Power behind Collections

Welcome to CodeSpread!

One of my favorite questions which I ask very frequently to test the candidate is “What is Collections?”

And I get almost all kind of answers, possibly available on planet Mars. But one answer which is expected on Earth is “Collections are elements which implements IEnumerable interface”.

But why this answer is so important! What the heck is IEnumerable?

IEnumerable is an interface which contains a method definition GetEnumerator(). This method has a return type of IEnumerator interface.


Interface IEnumerable

{

public IEnumerator GetEnumerator();

}

 

IEnumerator is the base interface for all nongeneric enumerators. Enumerators can be used to read the data in the collection, but they cannot be used to modify the underlying collection. So this Interface IEnumerator ensures read only access to the collection.

Although any element in a collection can be retrieved through its index property but a collection that implements IEnumerable can be used with a foreach statement to retrieve the elements.

The IEnumerator provides two abstract methods and a property to fetch a particular element from the collection.

Property:


Object Current { get; }

It’s a read only property. It retrieves the current individual element of the collection.

Methods:

MoveNext-


bool MoveNext()

As the name says, This method advances the enumerator to the next element of the collection.

Conditional Output:

True: if the enumerator was successfully advanced to the next element

False: if the enumerator has passed the end of the collection.

Reset-


void Reset()

As the name says, it resets the collection by setting the enumerator to its initial position, which is before the first element in the collection. The Reset method is provided for COM interoperability.

To make the things more simple, the complexity of the enumerators are avoided by using  foreach statement. This drives the iterations and there is no need to directly manipulate the enumerators.

Note:

  • Enumerators cannot be used to modify the underlying collection.

  • Enumerating through a collection is intrinsically not a thread-safe procedure.

  • Enumerator remains valid as long as the collection remains unchanged.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

  1. thanks for the tutorial
    I am having a problem.
    The feature “Create SQL server database” isn’t available , I can’t select it.
    Can you help, please ?