Implementing iterators with yield statements – .NET

using System;
using System.Collections.Generic;
using System.Collections;
using System.Text;

using System.Threading;

namespace CSharpBasics
{

    class IEnumerableCls
    {

        public void iterateIenumerable()
        {
            Console.WriteLine("Ienum1---");
            foreach (string s in new Ienum1())
                Console.WriteLine("    " + s);

            Console.WriteLine("Ienum2---");
            Ienum2 ie2 = new Ienum2();
            new Thread(new ThreadStart(delegate()
            {
                Thread.Sleep(500);
                ie2.stop = true; //As we are setting stop to be true here,
                //so Ienum2 should return yield break and set the end of enumerator.
            })).Start();

            foreach (string s in ie2)
                Console.WriteLine("    " + s);
        }

    }

    //yield return (for returning the next item) and
    //yield break (to signify the end of the iterator).
    public class Ienum1 : IEnumerable
    {
        #region IEnumerable Members

        public IEnumerator GetEnumerator()
        {
            yield return "First Obj"; //yield return stores the state
            //of Ienumerator in the compiler
            yield return "second cObj";
        }

        #endregion
    }

    class Ienum2 : IEnumerable
    {

        //The ****VOLATILE**** keyword indicates that a field
        //can be modified in the program
        //by something such as the operating system, the hardware,
        //or a concurrently executing thread.
        public volatile bool stop = false;

        #region IEnumerable Members

        public IEnumerator GetEnumerator()
        {
            for (int i = 0; i < 100; i++)
            {
                for (int j = 0; j < 100; j++)
                {
                    Thread.Sleep(50);
                    if (stop == true)
                        yield break;
                    yield return string.Format("{0}-{1}", i, j);
                }
            }
        }

        #endregion
    }

}

OUTPUT

**********************IEnumerable*****************
Ienum1---
    First Obj
    second cObj
Ienum2---
    0-0
    0-1
    0-2
    0-3
    0-4
    0-5
    0-6
    0-7
    0-8
Tags: , , ,

Leave a Reply

Your email address will not be published. Required fields are marked *

*
*