Implement generic IEnumerable

image_pdfimage_print


   


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

public class MyColl<T> : IEnumerable<T> {
    private T[] items;
    public MyColl( T[] items ) {
        this.items = items;
    }

    public IEnumerator<T> GetEnumerator() {
        foreach( T item in items ) {
            yield return item;
        }
    }

    IEnumerator IEnumerable.GetEnumerator() {
        return GetEnumerator();
    }

}

public class Test {
    static void Main() {
        MyColl<int> integers = new MyColl<int>( new int[] {1, 2, 3, 4} );

        foreach( int n in integers ) {
            Console.WriteLine( n );
        }
    }
}

           
          


This entry was posted in Generics. Bookmark the permalink.