Saturday, January 12, 2013

IEnumerable and IEnumerator


IEnumerable and IEnumerator are used to iterate over non generic collection.
IEnumerable exposes an enumerator.

IEnumerator has a property 'Current' that returns value of list item at current cursor position.
It has 2 methods
MoveNext() - Moves cursor to next item.
Reset() -  Reset cursor and send it to first item.

You can type cast a collection to IEnumerable or IEnumerator like list, array, array list.

List<int> myCol = List<int>();
mycol.add(5);
mycol.add(15);
mycol.add(20);

IEnumerable<int> ienmb = (IEnumerable<int>) myCol ;
IEnumerator<int> ienmr = (IEnumerator<int>) myCol ;

Now you can use these objects to iterate like this
Itration of IEnumerable
foreach(int i in ienmb) console.writeline(i);

Itration of IEnumerator
while(ienmr.MoveNext()) Console.Writeline(ienmr.Current.tostring());

You can also get enumrator object from enumrable object
IEnumerator<int> IEnumrObject = ienmb.GetEnumerator();

Differance b\w IEnumerable and IEnumerator
IEnumerable actually uses IEnumrator internally.
IEnumerator remember it's state, means it knows where is it's cursor position currently.
Syntactically IEnumerable easy to use.
If there is not any requirement that your collection object know about it's state than you can use IEnumerable.

No comments:

Post a Comment

CI/CD - Safe DB Changes/Migrations

Safe DB Migrations means updating your database schema without breaking the running application and without downtime . In real systems (A...