IEnumerable is the base interface for all collections that can be enumerated.
What is enumerable class in C#?
IEnumerable contains a single method, GetEnumerator, which returns an IEnumerator. IEnumerator provides the ability to iterate through the collection by exposing a Current property and MoveNext and Reset methods.
It is a best practice to implement IEnumerable and IEnumerator on your collection classes to enable the foreach statement.
Example program for IEnumerable in C#.NET
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
using System; using System.Collections; class Person : IEnumerable { private int[] list = { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; public int Age { get; set; } public string Name { get; set; } #region IEnumerable Members public IEnumerator GetEnumerator() { return list.GetEnumerator(); } #endregion } public class Program { public static void Main(string[] args) { Person personobj = new Person(); foreach(var n in personobj) { Console.WriteLine(n); } Console.Read(); } } |