Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are C# Iterators and Generators, and how could I utilize them

I am a VB.Net developer, kind of newbie in C#, While looking in C# documentation I came through Iterators and Generators, could not fully understand the use, I there anyone who can explain (in vb perceptive; if possible)

like image 280
Rajeev Avatar asked Sep 22 '10 09:09

Rajeev


People also ask

What is meant by C?

1. the third letter of the English alphabet, a consonant. 2. any spoken sound represented by the letter C or c, as in cat, race, or circle.

Why is C used?

C programming language uses blocks to separate pieces of code performing different tasks. This helps make programming easier and keeps the code clean. Thus, the code is easy to understand even for those who are starting out. C is used in embedded programming, which is used to control micro-controllers.

What is C and C++ means?

C++ is an object-oriented programming (OOP) language that is viewed by many as the best language for creating large-scale applications. C++ is a superset of the C language. A related programming language, Java, is based on C++ but optimized for the distribution of program objects in a network such as the Internet.


1 Answers

Iterators are an easy way to generate a sequence of items, without having to implement IEnumerable<T>/IEnumerator<T> yourself. An iterator is a method that returns an IEnumerable<T> that you can enumerate in a foreach loop.

Here's a simple example:

public IEnumerable<string> GetNames()
{
    yield return "Joe";
    yield return "Jack";
    yield return "Jane";
}

foreach(string name in GetNames())
{
    Console.WriteLine(name);
}

Notice the yield return statements: these statement don't actually return from the method, they just "push" the next element to whoever is reading the implementation.

When the compiler encounters an iterator block, it actually rewrites it to a state machine in a class that implements IEnumerable<T> and IEnumerator<T>. Each yield return statement in the iterator corresponds to a state in that state machine.

See this article by Jon Skeet for more details on iterators.

like image 88
Thomas Levesque Avatar answered Sep 19 '22 03:09

Thomas Levesque