Understanding IEnumerable and IEnumerator in C#

In the previous articular I have told about What is .Net Framework?  Today i am going to tell you about  IEnumerable and IEnumerator in C#.

IEnumerable and IEnumerator in C#

Many developers are aware of IEnumerable and IEnumerator but there are many other that don't have any idea of them.Basically IEnumerable and IEnumerator are two interfaces provided by .Net Framework that provides a way for iteration(loop) on object or type.All the collection provided by .Net framework are enumerable because they implement the IEnumerable interface.

If you declare a class and inherits IEnumerable interface that means you can iterate on this class type.

IEnumerable  interface has one method called GetEnumerator() that return an other interface called IEnumerator.

Below code will give you the clear idea -

GetEnumerator() methods return a IEnumerator type that is used to iterate on a type.

Above code is the signature of IEnumerator that has three members.(2 methods and one property)

void Reset()
bool MoveNext()
object Current (default set to -1 minus one)

Movenext method is used for iteration over object. Current property gives current element while iteration. Reset method sets the current property value to -1 to start the iteration again.

Below is the simplest example to understand IEnumerable and IEnumerator.


From above example it is clear that both interfaces are used to iterate over object/types.The only difference between IEnumerable and IEnumerator is that IEnumerator can not preserve state of current element while iteration,but IEnumerator has Current property that gives the current state of iteration.


I hope you have liked IEnumerable and IEnumerator in C# tutorial. I would like to have feedback from you. Your feedback, question ,queries or comments  are always welcome.

Thanks.
Understanding IEnumerable and IEnumerator in C# Understanding IEnumerable and IEnumerator in C# Reviewed by CodiBucket on 08:12 Rating: 5

No comments:

Facebook

Powered by Blogger.