July 06, 2013

Implementing IEnumerable

I've found myself needing to implement IEnumerable time and time again, so I'm just putting up a fun reference for myself to follow in the future.

My data:
public class IceCream {
  string _flavor;
  public string Flavor {
    get { return _flavor; }
    set {
      _flavor = value;
    }
  }

  public IceCream(string flavor) {
    _flavor = flavor;
  }

  public override string ToString() {
    return _flavor;
  }
}

The class that implements IEnumerable:
public class Menu<T> : IEnumerable<T> {
  List<T> rep = new List<T>();

  public Menu() { }

  public void Add(T item) {
    rep.Add(item);
  }

  public Menu(IEnumerable<T> collection) {
    foreach (T item in collection)
      rep.Add(item);
  }

  public IEnumerator<T> GetEnumerator() {
    foreach (T item in collection)
      yield return item;

    // return rep.GetEnumerator() works as well
  }

  IEnumerator IEnumerable.GetEnumerator() {
    return GetEnumerator();
  }
}

And now for the fun:
static void Main() {
  var Vanilla = new IceCream("vanilla");
  var Chocolate = new IceCream("chocolate");
  var CookieDough = new IceCream("cookie dough");
  var SaltyCaramel = new IceCream("salty caramel");

  var menu = new Menu<IceCream>() { Vanilla, Chocolate, CookieDough, SaltyCaramel };

  foreach (var i in menu)
    Console.WriteLine(i.ToString());
}

With the awesome output:
vanilla
chocolate
cookie dough
salty caramel

yay