Friday, April 11, 2008

Statement "yield".

    When we want to use operator foreach, but want to hide details of implementation we can use interface IEnumerable.

     Review next sample:

Let's display list of cities:

Cities cities = new Cities();
foreach (string city in cities)
{
Trace.WriteLine("city: " + city);
}



where class Cities is implemented:



public class Cities
{
readonly string[] cities = { "London", "Paris", "Rome", "Jerusalem" } ;
public IEnumerator GetEnumerator()
{
return cities.GetEnumerator();
}
}



normalOrder



Seems enough simple.


Now we need display cities in reverse order



Trace.WriteLine("Reverse order: ");
foreach (string city in cities.Reverese)
{
Trace.WriteLine("city: " + city);
}



reverseOrder



To receive reverse order we can add property Reverse:



public IEnumerable<string> Reverese
{
get
{
for (int i = cities.Length - 1; i >= 0; i--)
{
yield return cities[i];
}
}
}





Reference:



yield (C# Reference)



Create Elegant Code with Anonymous Methods, Iterators and Partial Classes.

No comments: