The only formal requirement is that it has a method called GetEnumerator() that returns something that has the SomeType Current {get;} property and the bool MoveNext() method. However, as a rule, this is achieved by implementing the IEnumerable / IEnumerable<T> interface. In fact, it is expected that you will implement this interface (the old method was really intended as pre-generation), and using this interface will allow consumers to use your collection with things like LINQ and collection initializers.
In interesting cases, the easiest way to implement this is to use an โiterator blockโ. For instance:
class Foo : IEnumerable<int> { IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public IEnumerator<int> GetEnumerator() { yield return 16; yield return 12; yield return 31;
source share