How to Create and Use of Iterators, yield: CSharp Programming

January 08, 2014 , 0 Comments

Programmer often use some type of iterators that are used to iterate steps in the programming language. An iterator often use yield keyword to return individual element, this is possible only if it have the current location in the cache.

C# Programming uses these iterators to execute some steps continuously like returning a value continuously from a method. Following program is creating an iterator in c# language.

public Form()
foreach (int number in SomeNumbers())
string str = number.ToString() + " ";
public static System.Collections.IEnumerable SomeNumbers()
yield return 1;
yield return 2;
yield return 3;

Yield keyword keeps the current position of the currently executing statement, so that the iteration can be performed.

Here Foreach keyword is used for looping statements in c# programming language, but it is also used as iterators. Each time when the SomeNumbers() method is called in this loop, the yield keyword will return the specified number and will back to the current position.

That is why the resulting string in str variable will be "1 2 3". There may be many ways to creating iterators like:

Using Collection Class: As the well-known class collection is used to automatically called GetEnumerator method which returns IEnumerable type of data. The same process can be easily implemented using this collection class.

Using Generic List: As GetEnumerator method returns an array of specified elements. Generic method is inherited from IEnumerable interface. Using this method iterators can easily be implemented as in above program.

Subhash Sharma

Some say he’s half man half fish, others say he’s more of a seventy/thirty split. Either way he’s a fishy bastard. Google