Previous Page
Next Page

Chapter 18 Quick Reference

To

Do this

Example

Make a class enumerable, allowing it to support the foreach construct.

Implement the IEnumerable interface and provide a GetEnumerator method that returns an IEnumerator object.

public class Tree<T>:IEnumerable<T>
{
    ...
    IEnumerator<T> GetEnumerator()
    {
        ...
    }
}

Implement an enumerator not by using an iterator.

Define an enumerator class that implements the IEnumerator interface and that provides the Current property and the MoveNext (and Reset) methods.

public class TreeEnumerator<T> :
IEnumerator<T>
{
    ...
    T Current
    {
        get
        {
            ...
        }
    }

    bool MoveNext()
    {
        ...
    }
}

Define an enumerator by using an iterator.

Implement the enumerator by using the yield statement indicating which items should be returned and in which order.

IEnumerator<T> GetEnumerator()
{
   for (...)
      yield return ...
}

Previous Page
Next Page