Using yield to implement an IEnumerator


using System;
using System.Collections;
public class MyCollection : IEnumerable
{
    int[] data = { 1, 2, 3 };

    public IEnumerator GetEnumerator()
    {
        foreach (int i in data)
            yield return i;
    }
}

class Sample
{
    public static void Main()
    {
        foreach (int i in new MyCollection())
            Console.WriteLine(i);

    }
}

The output:


1
2
3
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.