IEnumerator Example (Static Collection) : IEnumerator « Class Interface « C# / C Sharp






IEnumerator Example (Static Collection)

 

using System;
using System.Collections;
public class SimpleCollection : IEnumerable {

    public SimpleCollection(object[] array) {
        items = array;
    }

    public IEnumerator GetEnumerator() {
        return new Enumerator(this);
    }

    private class Enumerator : IEnumerator {

        public Enumerator(SimpleCollection obj) {
            oThis = obj;
            cursor = -1;
        }

        public bool MoveNext() {
            ++cursor;
            if (cursor > (oThis.items.Length - 1)) {
                return false;
            }
            return true;
        }


        public void Reset() {
            cursor = -1;
        }

        public object Current {
            get {
                if (cursor > (oThis.items.Length - 1)) {
                    throw new InvalidOperationException(

                        "Enumeration already finished");
                }
                if (cursor == -1) {
                    throw new InvalidOperationException(
                        "Enumeration not started");
                }
                return oThis.items[cursor];
            }
        }

        private int cursor;
        private SimpleCollection oThis;
    }


    private object[] items = null;
}

 








Related examples in the same category

1.iterates two collections simultaneously
2.yield IEnumerator
3.Collection is iterated using the IEnumerator interface