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

What is typeof undefined?

505


Is lazy thread safe c#?

503


What is difference between dictionary and list in c#?

454


Is string nullable c#?

499


What do you mean by winforms in c#?

503






What is a virtual property. Give an example?

515


Explain the difference between abstract class and interface.

596


Is dll a library?

488


Are arrays value types or reference types?

535


Can main method be final?

469


What is arraylist class in c#?

529


What is regex c#?

489


Why is static constructor called first?

477


Is c# scripting language?

505


There were a lot of questions asked, so I will list the topic (and add a what is "topic" and know pros/cons). Extreme programming, what is a transaction, various SDLC design approaches, what is a namespace, define a good test case, what is a stored proc, webservice? design patterns? linker? compiler? access modifiers? stack vs. queue? arrays vs. linked lists? sorting algorithms? recursion? OOP principles?

1583