Difference between IEnumerable and IEnumerator part-2

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

In this previous part we have discussed what is IEnumerable and IEnumerator with example.
in this Section we will discuss what are the basic diffrence between these two, and when we need to use this.
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");
Difference:

1. IEnumerable actually uses IEnumerator. i.e IEnumerable uses IEnumerator internally through GetIEnumerator.
And the Syna

Example:
IEnumerator weekIterator = weekenum.GetEnumerator();
while(weekIterator.MoveNext())
{
Console.WriteLine(weekIterator.Current.ToString());
}
2. The biggest difference is states, i.e. IEnumerable does not remember the cursor state i.e currently row which is iterating through, where I enumerator does.

# Example 1:
Enumerator :
public static void EnumeratorDemo()
{
IEnumerable weekenum = (IEnumerable)weekObj;
IEnumerator weekIterator = weekenum.GetEnumerator();
DisplayDaysSunToWed(weekIterator);
}
static void DisplayDaysSunToWed(IEnumerator obj)
{
while (obj.MoveNext())
{
Console.WriteLine(obj.Current.ToString());
if(obj.Current.Equals("Wednesday"))
{
DisplayDaysThrusToRest(obj);
}
}
}
static void DisplayDaysThrusToRest(IEnumerator obj)
{
while (obj.MoveNext())
{
Console.WriteLine(obj.Current.ToString());
}
}
static void Main(string[] args)
{
IEnuDiffrence.EnumeratorDemo();
Console.Read();
}

The above code will return below result

Sunday
Monday
Tuesday
Wednesday
Thrusday
Friday
Saturday

Continue in part 3


Asked In: Many Interviews | Alert Moderator 

Comments or Responses

Login to post response