Difference between IEnumerable and IEnumerator Part 1

 Posted by dhirenkaunar-15094 on 5/9/2012 | Category: C# Interview questions | Views: 9679 | Points: 40
Answer:

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> ();
weekObj.Add("Sunday");
weekObj.Add("Monday");
weekObj.Add("Tuesday");
weekObj.Add("Wednesday");
weekObj.Add("Thrusday");
weekObj.Add("Friday");
weekObj.Add("Saturday");

IEnumerable

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)
{
Console.WriteLine(day);
}
IEnumerator
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();

if (weekIterator.MoveNext())
{
Console.WriteLine(weekIterator.Current.ToString());
}

Continue with part 2


Asked In: Many Interviews | Alert Moderator 

Comments or Responses

Login to post response