using System.Collections;
using System.Collections.Generic;
public static void Main()
Console.WriteLine("\r\n\r\nNo iterator, so MontherMonkey can't enumerate children with foreach==========================");
MontherMonkey<Monkey> mom = new MontherMonkey<Monkey>();
IMonkey Tobby = mom.GiveBirth("Tobby");
IMonkey Jack = mom.GiveBirth("Jack");
IMonkey Gordo = mom.GiveBirth("Gordo");
Console.WriteLine("\r\n\r\nEnumerableMontherMonkey implements IEnumerable so foreach is OK==========================");
EnumerableMontherMonkey<Monkey> enumerableMom = new EnumerableMontherMonkey<Monkey>();
Tobby = enumerableMom.GiveBirth("Tobby");
Jack = enumerableMom.GiveBirth("Jack");
Gordo = enumerableMom.GiveBirth("Gordo");
foreach (IMonkey monkey in enumerableMom)
Console.WriteLine($"{monkey}");
string Name { get; set; }
public class Monkey : IMonkey
public int Age { get; set; }
public string Name { get; set; }
public int HaveBirthday()
public override string ToString()
return ($"My name is {Name}, I am a {this.GetType().Name} and I'm {Age} years old");
public class MontherMonkey<T>: Monkey where T: class, IMonkey, new()
protected List<T> Children { get; set; } = new List<T>();
public T GiveBirth(string Name)
T newMonkey = new T { Name = Name, Age = 0 };
public class EnumerableMontherMonkey<T> : MontherMonkey<T>, IEnumerable<T> where T : class, IMonkey, new()
public IEnumerator<T> GetEnumerator()
for (int index = 0; index < Children.Count; ++index)
yield return Children[index];
IEnumerator IEnumerable.GetEnumerator()