If you are using a collection List<T> or even arraylist within a class, why would you want to create your own enumeration class when you can just implement IEnumerable and return the enumerator. I see examples online where people create their own enumerable class and implement current, movenext etc…
If you are using a collection List<T> or even arraylist within a class, why
Share
Well, if you have a collection class you may not be just wrapping some other collection that is Enumerable and will return exactly what you should.
That said, I always prefer to use the yield keyword even for manually defining an enumerable. Most examples of people defining current/move next simply don’t know about yield or how to use it. (I once implemented an enumerable class defining Current/Move next for that exact reason.)
Another case could be that the underlying collection is old and doesn’t implement
IEnumerable<T>but justIEnumerable. If your collection is strongly typed you’ll want to do more than just return their enumerator (at the very least it will be a.Cast<T>()call).If you do have an underlying collection it may also be a collection of some private nested class (possibly some sort of custom key-value-pair) that you don’t want to publicly expose. This is a case where you may need to return a .Select call rather than just passing on the existing enumerator (but most likely wouldn’t need to actually implement your own iterator).