Shiman’s Weblog

Collecting stones from the sea-shore.

C# .NET Iterator Example : Reverse Iteration

The following example iterates a collection forward and reverse. Two iterators are exposed for this reason. GetEnumerator exposes the standard forward iterator. The reverse iterator is implemented in the Reverse property. Because the property returns IEnumerable, the Reverse property is both an enumerable and enumerator object. When an iterator method returns IEnumerable, the nested class generated by the compiler is implemented as both an enumerable and enumerator object. In Main, there are two foreach loops: The first foreach loop uses the forward iterator, whereas the reverse iterator is requested in the second loop:

using System;

using System.Collections.Generic;

 

namespace Examples.Iterators

{

    public class Program

    {

        public static void Main()

        {

            Console.WriteLine(“Forward List”);

            MyClass obj = new MyClass();

            foreach (int item in obj)

            {

                Console.Write(item);

            }

 

            Console.WriteLine(“\nReverse List”);

            foreach (int item in obj.Reverse)

            {

                Console.Write(item);

            }

 

            Console.ReadKey();

        }

    }

 

    public class MyClass

    { 

        private int[] list1 = new int[] { 0, 2, 4, 6, 8 };

 

        public IEnumerator<int> GetEnumerator()

        {

            for (int index = 0; index < 5; ++index)

            {

                yield return list1[index];

            }

        }

 

        public IEnumerable<int> Reverse

        {

            get

            {

                for (int index = 4; index >= 0; –index)

                {

                    yield return list1[index];

                }

            } 

        }

    }

}

 

August 1, 2008 Posted by shiman | C#.Net, Computer Science, OOP, Programming | , , , , , , , , , | 1 Comment