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?
expands approximately to
(In reality, the expansion of the
foreachstatement performed by the C# compiler is a bit more complicated; see Theforeachstatement.)