user48408
user48408

Reputation: 3364

When to create your own IEnumerable class

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...

Upvotes: 3

Views: 1074

Answers (3)

Bruno Silva
Bruno Silva

Reputation: 3097

Let's say you want to iterate through the lines of a files and you do not want to load them all in memory. You could return an IEnumerable<string> that will read the next line on demand instead of loading everything into memory. I also prefer using yield for this type of situations just like @Servy mentioned.

Upvotes: 3

Brad Rem
Brad Rem

Reputation: 6026

Is it possible that those examples are pre-generics? I can see that if you weren't using generics you would then be forced to implement IEnumerable and implement it's methods.

Upvotes: 0

Servy
Servy

Reputation: 203850

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 just IEnumerable. 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).

Upvotes: 7

Related Questions