Iterators in .NET


IEnumerator e = things.GetEnumerator();
while(e.MoveNext())
{
  Thing t = (Thing)e.Current;
  ...
}


for(IEnumerator e = things.GetEnumerator(); e.MoveNext(); )
{
  Thing t = (Thing)e.Current;
  ...
}


foreach(Thing t in things)
{
  ...
}
.NET is rather more overt than Python. Its iterators are something you can see and use directly, except that it calls them enumerators. Ah well.

Not quite sure why but don't think I've ever seen the for loop form ever in the wild. The while form seems to be the only one people use.

Can be used in an explicit or implicit way. For foreach, there's some duck-typiness coming into play. There's an IEnumerable interface, but you don't have to implement it, you just need a GetEnumerator method. The thing that's returned doesn't have to implement IEnumerator, just needs the methods with the right names and right signatures(ish) - can be typed.