figuring out c# enumerators
c#, ienumerable
Solution
foreach (Car myCar in cars)
{
Console.WriteLine("{0} is going {1} km/h", myCar.Name, myCar.CurrentSpeed);
}
expands approximately to
IEnumerator i = cars.GetEnumerator();
while (i.MoveNext())
{
Car myCar = (Car)i.Current;
Console.WriteLine("{0} is going {1} km/h", myCar.Name, myCar.CurrentSpeed);
}
(In reality, the expansion of the `foreach` statement performed by the C# compiler is a bit more complicated; see The `foreach` statement.)
Problem
I'm trying to understand enumerators using following example ``` public class Garage : IEnumerable { private Car[] cars = new Car[4]; public Garage() { cars[0] = new Car() { Id = Guid.NewGuid(), Name = "Mazda 3", CurrentSpeed = 90 }; cars[1] = new Car() { Id = Guid.NewGuid(), Name = "Mazda 6", CurrentSpeed = 80 }; } public IEnumerator GetEnumerator() { // return the array object's IEnumerator return cars.GetEnumerator(); } } static void Main(string[] args) { IEnumerator i = cars.GetEnumerator(); i.MoveNext(); Car myCar = (Car)i.Current; Console.WriteLine("{0} is going {1} km/h", myCar.Name, myCar.CurrentSpeed); Console.ReadLine(); } ``` How can I display on console second car without looping using foreach?