Hi Friends,
Today in this section, we’ll see IEnumerable
Here, enumerator uses three basic properties to iterate in the list and that is MoveNext(),reset and Current. MoveNext() will iterate till the collection ends and Current will set the subsequent item to current. Now, let’s see the same in action.
Now, consider the scenario of foreach(). As shown below in the example foreach() is pretty straight forward, i could have used the same in main method directly as i was using in the previous examples. However, i just wanted to emphasize on one point that foreach() internally replaces the code with with the previous example of IEnumerator
and offcourse result will be the same only.
Now, there is one exception to this, if the compiler notices that collection which we are iterating through is Array, then it will simply convert the foreach() method to to for loop than IEnumeartor
One more point is, enumeration is read only operation, so if you tries to modify the collection on the fly and iterate through, this won’t allow.
However, the above restriction is not applicable for all the collections. For example, if i change the same to Array and run the again, then compiler won’t complain. However, one point to note that its not a good practice to modify the element while iterating and the reason for this is foreach() for arrays gets converted into for loop, hence modification allowed in that.
Thanks for joining me.
Rahul sahay,
Happy Coding
Don’t Support Index. Use IEnumerator
karan monga recently posted…Getting started with LINQ