implement generic IEnumerable<>
Published: 26. October 2011 | Updated: 26. October 2011License: Microsoft Public License (MS-PL)
Categories: Framework » Generics, Implementations
Tags: C# Collections Design Patterns Generics
Import namespaces
using System.Collections; using System.Collections.Generic;
Implementation
public class MyClass : IEnumerable<string> { 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<string> 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
b
c
| Send us feedback about this snippet » |





