How to

implement non-generic IEnumerable

Published: 26. October 2011 | Updated: 26. October 2011
License: Microsoft Public License (MS-PL)
Categories: Implementations
Tags: C# Collections Design Patterns
Was this snippet helpful for you? YESYES / NONO

Import namespace

using System.Collections;

Implementation

public class MyClass : IEnumerable
{
    private readonly string[] _items;

    public MyClass(string[] items)
    {
        _items = new string[items.Length];
        for (int i = 0; i < items.Length; i++)
        {
            _items[i] = items[i];
        }
    }

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

    public IEnumerator GetEnumerator()
    {
        foreach (var item in _items)
        {
            yield return item;
        }
    }
}

Use

var myClass = new MyClass(new[] { "a", "b", "c" });

foreach (string value in myClass)
{
    Console.WriteLine(value);
}
Console Output:
a
b
c
Send us feedback about this snippet »



Related Snippets: