Named Iterator C# with Example
using System; using System.Collections; namespace CSharpInterface { public class Watch { internal byte hour, minute; internal string name; } class WatchArray : IEnumerable { Watch[] RoyalWatches = new Watch[4]; public WatchArray() { RoyalWatches[0] = new Watch(){hour=12, minute=0, name="HMT"}; RoyalWatches[1] = new Watch(){hour=10, minute=10, name="SONATA"}; RoyalWatches[2] = new Watch(){hour=5, minute=40, name="RADO"}; RoyalWatches[3] = new Watch(){hour=3, minute=0, name="TITAN"}; } public IEnumerator GetEnumerator() { foreach(Watch x in RoyalWatches) yield return x; } public IEnumerable GetWatch(bool returnReversed=false) { if(returnReversed) { for(int i=RoyalWatches.Length; i!=0; i--) yield return RoyalWatches[i-1]; } else { foreach( Watch w in RoyalWatches) yield return w; } } } class UsingWatchArray { public static void Main(string[] args) { WatchArray Watches = new WatchArray(); //Get Watches using GetEnumerator() Method foreach(Watch x in Watches) { Console.WriteLine("Time of {0} - {1}:{2}", x.name, x.hour, x.minute); } Console.WriteLine(); //Get Watches in Reverse using Named Iterator GetWatch() Method foreach(Watch x in Watches.GetWatch(true)) { Console.WriteLine("Time of {0} - {1}:{2}", x.name, x.hour, x.minute); } } } }