Enumerations


Using the foreach statement you can iterate elements of a collection without the need to know the number of elements inside the collection by using an enumerator. Figure 5-7 shows the relationship between the client invoking the foreach method and the collection. The array or collection implements the IEnumerable interface with the GetEnumerator() method. The GetEnumerator() method returns an enumerator implementing the IEnumerable interface. The interface IEnumerable then is used by the foreach statement to iterate through the collection.

image from book
Figure 5-7

Tip 

The GetEnumerator() method is defined with the interface IEnumerable . The foreach statement doesn’t really need this interface implemented in the collection class. It’s enough to have a method with the name GetEnumerator() that returns an object implementing the IEnumerator interface.

IEnumerator Interface

The foreach statement uses the methods and properties of the IEnumerator interface to iterate all elements in a collection. The properties and methods from this interface are defined with the following table.

Open table as spreadsheet

IEnumerator Interface Properties and Methods

Description

MoveNext()

The MoveNext() method moves to the next element of the collection and returns true if there’s an element. If the collection does not contain any more elements, the value false is returned.

Current

The property Current returns the element where the cursor is positioned.

Reset()

The method Reset() repositions the cursor to the beginning of the collection. Many enumerators throw a NotSupportedException.

foreach Statement

The C# foreach statement is not resolved to a foreach statement in the IL code. Instead, the C# compiler converts the foreach statement to methods and properties of the IEnumerable interface. Here’s a simple foreach statement to iterate all elements in the persons array and to display them person by person.

  foreach (Person p in persons) {    Console.WriteLine(p); } 

The foreach statement is resolved to the following code segment. First, the GetEnumerator() method is invoked to get an enumerator for the array. Inside a while loop - as long as MoveNext() returns true - the elements of the array are accessed using the Current property:

  IEnumerator enumerator = persons.GetEnumerator(); while (enumerator.MoveNext()) {    Person p = (Person)enumerator.Current;    Console.WriteLine(p); } 

yield Statement

C# 1.0 made it easy to iterate through collections by using the foreach statement. With C# 1.0, it was still a lot of work to create an enumerator. C# 2.0 adds the yield statement for creating enumerators easily.

yield return returns one element of a collection and moves the position to the next element, yield break stops the iteration.

The next example shows the implementation of a simple collection using the yield return statement. The class HelloCollection contains the method GetEnumerator(). The implementation of the GetEnumerator() method contains two yield return statements where the strings Hello and World are returned.

  using System; using System.Collections; namespace Wrox.ProCSharp.Arrays {    public class HelloCollection    {       public IEnumerator GetEnumerator()       {          yield return "Hello";          yield return "World";       }    } 

Important 

A method or property that contains yield statements is also known as iterator block. An iterator block must be declared to return an IEnumerator or IEnumerable interface. This block may contain multiple yield return or yield break statements; a return statement is not allowed.

Now it is possible to iterate through the collection using a foreach statement:

     public class Program    {       HelloCollection helloCollection = new HelloCollection();       foreach (string s in helloCollection)       {          Console.WriteLine(s);       }    } } 

With an iterator block the compiler generates a yield type, including a state machine, as shown with the following code segment. The yield type implements the properties and methods of the interfaces IEnumerator and IDisposable. In the sample, you can see the yield type as the inner class Enumerator. The GetEnumerator() method of the outer class instantiates and returns a new yield type. Within the yield type, the variable state defines the current position of the iteration and is changed every time the method MoveNext() is invoked. MoveNext() encapsulates the code of the iterator block and sets the value of the current variable so that the Current property returns an object depending on the position.

  public class HelloCollection {    public IEnumerator GetEnumerator()    {       Enumerator enumerator = new Enumerator();       return enumerator;    }    public class Enumerator : IEnumerator, IDisposable    {       private int state;       private object current;       public Enumerator(int state)       {          this.state = state;       }       bool System.Collections.IEnumerator.MoveNext()       {          switch (state)          {             case 0:                current = "Hello";                state = 1;                return true;             case 1:                current = "World";                state = 2;                return true;             case 2:                break;          }          return false;       }       void System.Collections.IEnumerator.Reset()       {          throw new NotSupportedException();       }       object System.Collections.IEnumerator.Current       {          get          {             return current;          }       }       void IDisposable.Dispose()       {       }    } } 

Now using the yield return statement it is easy to implement a class that allows iterating through a collection in different ways. The class MusicTitles allows iterating the titles in a default way with the GetEnumerator() method, in reverse order with the Reverse() method, and to iterate through a subset with the Subset() method:

  public class MusicTitles {     string[] names = {           "Tubular Bells", "Hergest Ridge",           "Ommadawn", "Platinum" };     public IEnumerator GetEnumerator()     {         for (int i = 0; i < 4; i++)         {             yield return names[i];         }     }     public IEnumerable Reverse()     {         for (int i = 3; i >= 0; i–)         {             yield return names[i];         }     }     public IEnumerable Subset(int index, int length)     {         for (int i = index; i < index + length; i++)         {             yield return names[i];         }     } } 

The client code to iterate through the string array first uses the GetEnumerator() method that you don’t have to write in your code as this one is used by default. Then the titles are iterated in reverse, and finally a subset is iterated by passing the index and number of items to iterate to the Subset() method:

  MusicTitles titles = new MusicTitles(); foreach (string title in titles) {     Console.WriteLine(title); } Console.WriteLine(); Console.WriteLine("reverse"); foreach (string title in titles.Reverse()) {     Console.WriteLine(title); } Console.WriteLine(); Console.WriteLine("subset"); foreach (string title in titles.Subset(2, 2)) {     Console.WriteLine(title); } 

With the yield statement you can also do more complex things, for example returning an enumerator from yield return.

With the TicTacToe game you have nine fields where the players alternating put a cross or a circle. These moves are simulated by the GameMoves class. The methods Cross() and Circle() are the iterator blocks for creating iterator types. The variable cross and circle are set to Cross() and Circle() inside the constructor of the GameMoves class. By setting these fields the methods are not invoked, but set to the interator types that are defined with the iterator blocks. Within the Cross() iterator block, information about the move is written to the console and the move number is incremented. If the move number is higher than 9, the iteration ends with yield break; otherwise, the enumerator object of the cross yield type is returned with each iteration. The Circle() iterator block is very similar to the Cross() iterator block; it just returns the circle iterator type with each iteration.

  public class GameMoves {     private IEnumerator cross;      private IEnumerator circle;     public GameMoves()     {         cross = Cross();         circle = Circle();     }     private int move = 0;     public IEnumerator Cross()     {         while (true)         {             Console.WriteLine("Cross, move {0}", move);             move++;             if (move > 9)                 yield break;             yield return circle;         }     }     public IEnumerator Circle()     {         while (true)         {             Console.WriteLine("Circle, move {0}", move);             move++;             if (move > 9)                 yield break;             yield return cross;         }     } } 

From the client program you can use the class GameMoves as follows. The first move is set by setting enumerator to the enumerator type returned by game.Cross(). enumerator.MoveNext invokes one iteration defined with the iterator block that returns the other enumerator. The returned value can be accessed with the Current property and is set to the enumerator variable for the next loop:

  GameMoves game = new GameMoves(); IEnumerator enumerator = game.Cross(); while (enumerator.MoveNext()) {     enumerator = (IEnumerator)enumerator.Current; } 

The outcome of this program shows alternating moves until the last move:

 Cross, move 0 Circle, move 1 Cross, move 2 Circle, move 3 Cross, move 4 Circle, move 5 Cross, move 6 Circle, move 7 Cross, move 8




Professional C# 2005 with .NET 3.0
Professional C# 2005 with .NET 3.0
ISBN: 470124725
EAN: N/A
Year: 2007
Pages: 427

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net