Saturday, September 15, 2007

Supporting "foreach" without implementing IEnumerable

Krzysztof Cwalina wrote a post detailing how have your class support the "foreach" loop without implementing the IEnumerable interface:

  1. Public GetEnumerator() method that returns a type with 2 members:
  2. The type will have a bool MoveMext() method.
  3. The type will have an Current property of type object.
Example:
class Foo {
public Bar GetEnumerator() { return new Bar(); }

public struct Bar {
public bool MoveNext() {
return false;
}
public object Current {
get { return null; }
}
}
}

No comments: