What are iterators?

Answer Posted / prem

An iterator is invoked from client code by using a foreach
statement.
An iterator is a section of code that returns an ordered
sequence of values of the same type.

An iterator can be used as the body of a method, an
operator, or a get accessor.

The iterator code uses the yield return statement to return
each element in turn. yield break ends the iteration
EXAMPLE
.............................................................
public class DaysOfTheWeek : System.Collections.IEnumerable
{
string[] days = { "Sun", "Mon", "Tue", "Wed", "Thr",
"Fri", "Sat" };

public System.Collections.IEnumerator GetEnumerator()
{
for (int i = 0; i < days.Length; i++)
{
yield return days[i];
}
}
}

class TestDaysOfTheWeek
{
static void Main()
{
// Create an instance of the collection class
DaysOfTheWeek week = new DaysOfTheWeek();

// Iterate with foreach
foreach (string day in week)
{
System.Console.Write(day + " ");
}
}
}
// Output: Sun Mon Tue Wed Thr Fri Sat

Is This Answer Correct ?    0 Yes 0 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

Is c# a technology?

488


Why static constructor is parameterless in c#?

593


What is the xml document structure?

467


Can a child class call the constructor of a base class?

543


What is the difference between list and array in c#?

462






How to use delegates with events?

546


What is jit (just in time)?

546


what will be the output of the given below coding. using System; public class Exercise { static void OddNumbers(int a) { if (a >= 1) { Console.Write("{0}, ", a); a -= 2; OddNumbers(a); } } public static int Main() { const int Number = 9; Console.WriteLine("Odd Numbers"); OddNumbers(Number); Console.WriteLine(); return 0; } }

3305


How to override a function in c#?

540


What is the main method?

473


What is the object class in c#?

483


What is generic delegate in c#?

451


Contrast System.String and System.Text.StringBuilder classes?

524


What is the base class in .net from which all the classes are derived from?

498


Define an array?

526