I am developing a collection class, which should implement IEnumerator and IEnumerable.
In my first approach, I implemented them directly. Now I have discovered the yield keyword, and I have been able to simplify everything a whole lot substituting the IEnumerator/IEnumerable interfaces with a readonly property Values that uses yield to return an IEnumerable in a loop.
My question: is it possible to use yield in such a way that I could iterate over the class itself, without implementing IEnumerable/IEnumerator?
I.e., I want to have a functionality similar to the framework collections:
List<int> myList = new List<int>();
foreach (int i in myList)
{
...
}
Is this possible at all?
Update: It seems that my question was badly worded. I don’t mind implementing IEnumerator or IEnumerable; I just thought the only way to do it was with the old Current/MoveNext/Reset methods.
You won’t have to implement
IEnumerable<T>orIEnumerableto getforeachto work – but it would be a good idea to do so. It’s very easy to do:The alternative which doesn’t implement
IEnumerable<T>would just call yourValuesproperty, but still providing aGetEnumerator()method:While this will work, it means you won’t be able to pass your collection to anything expecting an
IEnumerable<T>, such as LINQ to Objects.It’s a little-known fact that
foreachwill work with any type supporting aGetEnumerator()method which returns a type with appropriateMoveNext()andCurrentmembers. This was really to allow strongly-typed collections before generics, where iterating over the collection wouldn’t box value types etc. There’s really no call for it now, IMO.