Collection is iterated using the IEnumerator interface : IEnumerator : Class Interface C# Source Code


Custom Search

C# Source Code » Class Interface » IEnumerator »

 

Collection is iterated using the IEnumerator interface








    
 

using System;
using System.Collections;

public class Starter {
    public static void Main() {
        SimpleCollection simple = new SimpleCollection(new object[] { 1, 2, 3, 4, 5, 6, 7 });
        IEnumerator enumerator = simple.GetEnumerator();
        while (enumerator.MoveNext()) {
            Console.WriteLine(enumerator.Current);
        }
    }
}

public class SimpleCollection : IEnumerable {
    public SimpleCollection(object[] array) {
        items = array;
    }
    public IEnumerator GetEnumerator() {
        return new Enumerator(items);
    }

    private object[] items = null;
}
public class Enumerator : IEnumerator {
    public Enumerator(object[] items) {
        elements = new object[items.Length];
        Array.Copy(items, elements, items.Length);
        cursor = -1;
    }
    public bool MoveNext() {
        ++cursor;
        if (cursor > (elements.Length - 1)) {
            return false;
        }
        return true;
    }
    public void Reset() {
        cursor = -1;
    }
    public object Current {
        get {
            if (cursor > (elements.Length - 1)) {
                throw new InvalidOperationException("Enumeration already finished");
            }
            if (cursor == -1) {
                throw new InvalidOperationException(
                    "Enumeration not started");
            }
            return elements[cursor];
        }
    }

    private int cursor;
    private object[] elements = null;
}
 
    
   
  
   







HTML code for linking to this page:

Follow Navioo On Twitter

C# Source Code

 Navioo Class Interface
» IEnumerator