• Puzzle
  • Iterator
  • yield

Puzzle 2: iterators using the yield statement (intermediate)

Remove the iterator class from the listing and replace the call to the iterator class, inside the iteration sample(line 29), by using the yield operator of C#2.

The output of the Problem() method should remain the same.

using System;

using System.Collections;



namespace Puzzles

{



    public class Enumarators

    {

        public static void Problem()

        {

            var myValues = new[] { "a", "b", "c", "d" };

            var col = new IterationSample(myValues);

            foreach (var x in col)

            {

                Console.WriteLine(x);

            }

        }



        public class IterationSample : IEnumerable

        {

            internal object[] values;



            public IterationSample(object[] values)

            {

                this.values = values;

            }

            public IEnumerator GetEnumerator()

            {

                return new Iterator(this);  //Change this line by using yield

            }

        }



        public class Iterator:IEnumerator

        {

            IterationSample parent;

            int position;



            internal Iterator(IterationSample parent)

            {

                this.parent = parent;

                position = -1;

            }

            public bool MoveNext()

            {

                if (position != parent.values.Length)

                {

                position++;

                }

                return position < parent.values.Length;

            }

            public object Current

            {

                get

                {

                    if (position==-1 || position==parent.values.Length)

                    {

                     throw new InvalidOperationException();

                    }

                    return parent.values[position];

                }

            }

            public void Reset()

            {

                position = -1;

            }

        }

    }

}