I get the idea of IEnumerator which gives an abilty of iteration to a class. I get the idea of why GetEnumerable() is needed to use foreach statement. But I wonder why I need to implement IEnumerator while I can declare an array as an property? I am really confused and could use a good explanation. Here is my codeblock, the result is the same with and without IEnumerator implementation.
static void Main(string[] args)
{
Customer customer1 = new Customer
{
Name = "Marty",
Surname = "Bird",
Id = 1
};
Customer customer2 = new Customer
{
Name = "Hellen",
Surname = "Pierce",
Id = 2
};
Customers customers = new Customers();
customers.Add(customer1);
customers.Add(customer2);
//Using a property: This one works without an extra GetEnumerator implementation.
foreach (var item in customers.CustomerList)
{
Console.WriteLine(item.Name);
}
//Using with GetEnumerator()
foreach (Customer item in customers)
{
Console.WriteLine(item.Name);
}
}
class Customer
{
public int Id { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
}
class Customers:IEnumerable
{
private List<Customer> customerList = new List<Customer>();
public List<Customer> CustomerList { get=> customerList; }
public void Add(Customer p)
{
customerList.Add(p);
}
public IEnumerator GetEnumerator()
{
return customerList.GetEnumerator();
}
}