To support foreach in some classes – see example below
Ok
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 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace IEnumerable123 { class Program { static void Main(string[] args) { Garage carLot = new Garage(); foreach (Car c in carLot) { Console.WriteLine(c.Name); } // <<< Here !!! Console.ReadLine(); } } public class Garage: IEnumerable { private Car[] carArray = new Car[4]; public Garage() { carArray[0] = new Car("name1"); carArray[1] = new Car("name2"); carArray[2] = new Car("name3"); carArray[3] = new Car("name4"); } public IEnumerator GetEnumerator() { return carArray.GetEnumerator(); } } public class Car { public string Name{get; set;} public Car(string aname){ Name = aname; } } } |
Not Ok
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 34 35 36 37 38 39 40 41 42 43 44 |
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace IEnumerable123 { class Program { static void Main(string[] args) { Garage carLot = new Garage(); foreach (Car c in carLot) { Console.WriteLine(c.Name); } // Garage should support IEnumerator Console.ReadLine(); } } public class Garage { private Car[] carArray = new Car[4]; public Garage() { carArray[0] = new Car("name1"); carArray[1] = new Car("name2"); carArray[2] = new Car("name3"); carArray[3] = new Car("name4"); } } public class Car { public string Name{get; set;} public Car(string aname){ Name = aname; } } } |