Before Going for the difference between IEnumerable and IEnumerator , let first discuss what is IEnumerable and IEnumerator is with example. I am going to use the below list
List<string> weekObj = new List <string> ();
The IEnumerable interface is a generic interface that provides an abstraction for looping over elements.
In addition to providing foreach support, it allows you to tap into the useful extension methods in the System.Linq namespace, opening up a lot of advanced functionality
The IEnumerable interface contains an abstract member function called GetEnumerator() and return an interface IEnumerator on any success call.
Example: Traversing IEnumerable
IEnumerable weekenum = (IEnumerable)weekObj;
foreach (string day in weekenum)
IEnumerator provides two abstract methods and a property to pull a particular element in a collection. And they are Reset(), MoveNext() and Current The signature of IEnumerator members is as follows:
void Reset() : Sets the enumerator to its initial position, which is before the first element in the collection.
bool MoveNext() : Advances the enumerator to the next element of the collection.
object Current : Gets the current element in the collection.
Example : Traversing IEnumerator
IEnumerator weekIterator = weekObj.GetEnumerator();
Continue with part 2
Asked In: Many Interviews |