Difference between IEnumerable and IEnumerator part 3

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

# Example 2 :

IEnumerable:

public static void EnumeratorDemo()
{
IEnumerable weekenum = (IEnumerable)weekObj;
DisplayDaysSunToWed(weekenum);
}
static void DisplayDaysSunToWed(IEnumerator obj)
{
while (obj.MoveNext())
{
Console.WriteLine(obj.Current.ToString());
if(obj.Current.Equals("Wednesday"))
{
DisplayDaysThrusToRest(obj);
}
}
}
static void DisplayDaysSunToWed(IEnumerable obj)
{
foreach (string day in obj)
{
Console.WriteLine(day);
if (day.Equals("Wednesday"))
{
DisplayDaysThrusToRest(obj);
}
}
}
static void DisplayDaysThrusToRest(IEnumerable obj)
{
foreach (string day in obj)
{
Console.WriteLine(day);
}
}
The above code will return below result

Sunday
Monday
Tuesday
Wednesday
Sunday
Monday
Tuesday
Wednesday
Thrusday
Friday
Saturday
Thrusday
Friday
Saturday

Example 2 signifies that IEnumerable is not storing the current cursor state .
Lets debug the example2:

·Main function called DisplayDaysSunToWed(IEnumerable obj) this function prints the below value
Sunday
Monday
Tuesday
Wednesday
· Now the given condition become true 'day.Equals("Wednesday")' , so it will call DisplayDaysThrusToRest(IEnumerable obj) function , now this function will print the below value
Sunday
Monday
Tuesday
Wednesday
Thrusday
Friday
Saturday
· Then it come back to the function 1 ‘DisplayDaysSunToWed()’ , in this function the cursor position is in “Wednesday” , Now this function loop through the rest value mentioned below.

Thrusday
Friday
Saturday
·So the final result is as the above output

Note:
IEnumerable is useful when we have only iterate the value and IEnumerator is useful when we have to pass the iterator as parameter and has to remember the value.


Asked In: Many Interviews | Alert Moderator 

Comments or Responses

Login to post response